Example Code for Arduino-Read Serial Port Data
Last revision 2025/12/17
Hardware Preparation
- DFRduino UNO R3 (or similar) x 1
- Water-proof Ultrasonic Sensor (ULS) x1
- Connectors
Software Preparation
Wiring Diagram
Other Preparation Work
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;
unsigned char buffer_RTT[6] = {};
int Rage = 0;
float Temp = 0;
int Tflag = 0;
void setup() {
Serial.begin(57600); // Enable the serial port and set the band rate to 57600 bps
mySerial.begin(9600);
pinMode(LED_BUILTIN, OUTPUT);
digitalWrite(LED_BUILTIN, HIGH);
}
void loop() {
digitalWrite(LED_BUILTIN, HIGH);
delay(100);
digitalWrite(LED_BUILTIN, LOW);
delay(4);
digitalWrite(LED_BUILTIN, HIGH);
do{
for (int j = 0; j <= 5; j++){
col = mySerial.read();
buffer_RTT[j] = (char)col;
}
} while(mySerial.read() == 0xff);
mySerial.flush();
if(buffer_RTT[0]==0xff){
int cor;
cor=(buffer_RTT[0]+buffer_RTT[1]+buffer_RTT[2]+buffer_RTT[3]+buffer_RTT[4])&0x00FF;//Check
if(buffer_RTT[5]==cor)
{
Rage = (buffer_RTT[1] << 8) + buffer_RTT[2];
Tflag= buffer_RTT[3]&0x80;
if(Tflag==0x80){
buffer_RTT[3]=buffer_RTT[3]^0x80;
}
Temp = (buffer_RTT[3] << 8) + buffer_RTT[4];
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("============================== ");
}
Result
Was this article helpful?
