Example Code for Arduino-Read Serial Port Data
This project demonstrates how to read distance and temperature data from the SEN0301 Water-proof Ultrasonic Sensor using RS232 output mode with an Arduino board. Users will learn how to communicate with the sensor via serial and process the received data.
Hardware Preparation
- DFRduino UNO R3 (or similar) x 1
- Multi USB/RS232/RS485/TTL Converter V2.0 x 1
- Water-proof Ultrasonic Sensor (ULA) x 1
- Connectors
Software Preparation
Wiring Diagram
The internal probe surface is regarded as the detecting starting point by default. If you take the plane of the bell-mouth as starting point, then the distance will be the detected distance minus 40mm.
Sample Code
* ****************************************************
* @brief Water-proof Ultrasonic Sensor (ULS)
* @copyright [DFRobot](https://www.dfrobot.com), 2016
* @copyright GNU Lesser General Public License
* @author [Xiaoyu]([email protected])
* @version V1.0
* @date 2019-03-11
* GNU Lesser General Public License.
* All above must be included in any redistribution
* ****************************************************/
#include <SoftwareSerial.h>
SoftwareSerial mySerial(10, 11); // RX, TX
char col;// For storing data read from the serialport
unsigned char buffer_RTT[7] = {};
unsigned char buffer_coderead[]{0xFF,0x01,0x01,0x01};
int Rage = 0;
float Temp = 0;
int Tflag = 0;
void setup() {
Serial.begin(57600); // Enable serial port and set band rate to 57600 bps
mySerial.begin(9600);
pinMode(LED_BUILTIN, OUTPUT);
digitalWrite(LED_BUILTIN, HIGH);
}
void loop(){
do{
for (int j = 0; j <= 6; j++){
col = mySerial.read();
buffer_RTT[j] = (char)col;
}
} while(mySerial.read() == 0xFF);
mySerial.flush();
if(buffer_RTT[0]==0xFF){//Judge the first bit of the data
int cor;
cor=buffer_RTT[0]+buffer_RTT[1]+buffer_RTT[2]+buffer_RTT[3]+buffer_RTT[4]+buffer_RTT[5];
cor=cor&0x00FF;
if(buffer_RTT[6]==cor)
{
Rage = (buffer_RTT[2] << 8) + buffer_RTT[3];
Tflag= buffer_RTT[4]&0x80;
if(Tflag==0x80){
buffer_RTT[4]=buffer_RTT[4]^0x80;
}
Temp = (buffer_RTT[4] << 8) + buffer_RTT[5];
Temp = Temp/10;
}
else{
Rage = 0;
Temp = 0;
}
}
Serial.print("Rage : ");
Serial.print(Rage);//Output distance unit mm
Serial.println("mm");
Serial.print("Temperature: ");
if(Tflag ==0x80)
{
Serial.print("-");
}
Serial.print(Temp);//Output temperature
Serial.println("℃");
Serial.println("============================== ");
delay(100);
}
Result
Was this article helpful?
