Example Code for Arduino-Ultrasonic Ranging

This project demonstrates how to interface the Small Angle Ultrasonic Ranging Sensor (SEN0627) with an Arduino board to measure the distance to an obstacle or liquid. The sensor communicates via UART, and the Arduino reads the distance data, validates it using a checksum, and prints the result to the serial monitor. Users will learn how to use SoftwareSerial for UART communication, handle sensor data frames, and implement basic data validation.

Hardware Preparation

Name Model/SKU Quantity Purchase Link
DFRduino UNO R3 DFR0009 1 DFRduino UNO R3
Small Angle Ultrasonic Ranging Sensor-8m SEN0627 1 Small Angle Ultrasonic Ranging Sensor-8m

Software Preparation

Wiring Diagram

Arduino Wiring diagram

Other Preparation Work

Ensure the sensor is connected to the Arduino as per the Wiring Diagram. No additional libraries or configurations are required for this example.

Sample Code

#include <SoftwareSerial.h>
unsigned char buffer_RTT[4] = {0};
uint8_t CS;
#define COM 0x55
int Distance = 0;
SoftwareSerial mySerial(7, 8); 
void setup() {
  Serial.begin(9600);
  mySerial.begin(9600);
}
void loop() {
  mySerial.write(COM);
  delay(10);
  if(mySerial.available() > 0){
    delay(4);
    if(mySerial.read() == 0xff){    
      buffer_RTT[0] = 0xff;
      for (int i=1; i<4; i++){
        buffer_RTT[i] = mySerial.read();   
      }
      CS = buffer_RTT[0] + buffer_RTT[1]+ buffer_RTT[2];  
      if(buffer_RTT[3] == CS) {
        Distance = (buffer_RTT[1] << 8) + buffer_RTT[2];
        Serial.print("Distance:");
        Serial.print(Distance);
        Serial.println("cm");
      }
    }
  }
}

Result

If there is an obstacle or liquid in front of the sensor, the serial port prints out the distance value between the sensor and the obstacle or liquid.

Arduino Serial port printing data map

Was this article helpful?

TOP