Example Code for Arduino-Ultrasonic Ranging
This project demonstrates how to use the Ultrasonic Ranging Sensor (5m) with Arduino to read real-time distance values. Users will learn how to communicate with the sensor via RS485 using the Modbus protocol and display the distance on the serial monitor.
Hardware Preparation
| Name | Model/SKU | Quantity | Purchase Link |
|---|---|---|---|
| DFRduino UNO R3 (or similar) | DFR0838 | 1 | DFRduino UNO R3 |
| RS485 Shield for Arduino | DFR0259 | 1 | RS485 Shield for Arduino |
| Ultrasonic Ranging Sensor(5m) | SEN0592 | 1 | Ultrasonic Ranging Sensor(5m) |
Software Preparation
- Arduino IDE: No additional library installation is required for this project.
Wiring Diagram
Before burning the code, please switch the transceiver mode switch of the expansion board to AUTO, and the run/compile switch to OFF; after burning the code, switch the run/compile switch to ON, and select the serial port baud rate of 115200.

Other Preparation Work
- Before uploading the program:
- Set the RS485 Shield's transceiver mode switch to
AUTO. - Set the RS485 Shield's run/compile switch to
OFF.
- Set the RS485 Shield's transceiver mode switch to
- After uploading the program:
- Set the RS485 Shield's run/compile switch to
ON. - Select a 115200 baud rate for the serial port in the Arduino IDE.
- Set the RS485 Shield's run/compile switch to
Sample Code
uint8_t Com[8] = {0x01,0x03,0x01,0x01,0x00,0x01,0xd4,0x36};
void setup()
{
Serial.begin(115200);
}
void loop()
{
int Distance =readDistance();
Serial.print("Distance = ");
Serial.print(Distance);
Serial.println(" mm");
delay(500);
}
int readDistance(void)
{
uint8_t Data[10] = {0};
uint8_t ch = 0;
bool flag = 1;
int Distance = 0;
while (flag) {
delay(100);
Serial.write(Com, 8);
delay(10);
if (readN(&ch, 1) == 1) {
if (ch == 0x01) {
Data[0] = ch;
if (readN(&ch, 1) == 1) {
if (ch == 0x03) {
Data[1] = ch;
if (readN(&ch, 1) == 1) {
if (ch == 0x02) {
Data[2] = ch;
if (readN(&Data[3], 4) == 4) {
if (CRC16_2(Data, 5) == (Data[5] * 256 + Data[6])) {
Distance = Data[3] * 256 + Data[4];
//Serial.println(Distance);
flag = 0;
}
}
}
}
}
}
}
}
Serial.flush();
}
return Distance;
}
uint8_t readN(uint8_t *buf, size_t len)
{
size_t offset = 0, left = len;
int16_t Tineout = 500;
uint8_t *buffer = buf;
long curr = millis();
while (left) {
if (Serial.available()) {
buffer[offset] = Serial.read();
offset++;
left--;
}
if (millis() - curr > Tineout) {
break;
}
}
return offset;
}
unsigned int CRC16_2(unsigned char *buf, int len)
{
unsigned int crc = 0xFFFF;
for (int pos = 0; pos < len; pos++)
{
crc ^= (unsigned int)buf[pos];
for (int i = 8; i != 0; i--)
{
if ((crc & 0x0001) != 0)
{
crc >>= 1;
crc ^= 0xA001;
}
else
{
crc >>= 1;
}
}
}
crc = ((crc & 0x00ff) << 8) | ((crc & 0xff00) >> 8);
return crc;
}
Result
View the distance value detected by the sensor through the serial port.

Was this article helpful?
