Example Code for Arduino-Ultrasonic Distance Measurement

Last revision 2026/01/19

This example is the ultrasonic distance measurement of the module. The mainboard outputs a high-level about tens of microseconds to trigger the sensor to start ranging. Then, the sensor will output a high-level pulse proportional to the ultrasonic flight time. The distance can be easily obtained after a simple calculation by detecting high-level time.

Hardware Preparation

  • DFRduino UNO R3 (or similar) x 1
  • URM09 Ultrasonic Sensor(Gravity Trig) x1
  • Gravity 3Pin digital sensor cable x1

Software Preparation

Wiring Diagram

Connect the sensor to your Arduino mainboard with a Gravity 3Pin digital sensor cable.

Connection Diagram

Other Preparation Work

URM09 Ultrasonic Sensor(Gravity Trig) uses digital IO port to trigger distance measurement, and the tringger signal and received signal shares one pin by TMD(Time Division Multiplexing):

Timing Diagram

  1. The sensor is in input mode at this time, and the host needs to be set to output mode. Send 10us high pulse trigger signal from the host, and then change the host port status to input, wait for the sensor to return signal.

  2. The output high-level time of the sensor is equal to ultrasonic flight time(longest pulse width time: 35000us).

Sample Code

/*!
       This example is the ultrasonic distance measurement of the module.

       Copyright   [DFRobot](http://www.dfrobot.com), 2020
       Copyright   GNU Lesser General Public License

       version  V1.0
       date  29/10/2020
*/

#define    VELOCITY_TEMP(temp)       ( ( 331.5 + 0.6 * (float)( temp ) ) * 100 / 1000000.0 ) // The ultrasonic velocity (cm/us) compensated by temperature

int16_t trigechoPin = 11;
uint16_t distance;
uint32_t pulseWidthUs;
void setup() {
  Serial.begin(9600);
  delay(100);
}
void loop() {
  int16_t  dist, temp;
  pinMode(trigechoPin,OUTPUT);
  digitalWrite(trigechoPin,LOW);

  digitalWrite(trigechoPin,HIGH);//Set the trig pin High
  delayMicroseconds(10);     //Delay of 10 microseconds
  digitalWrite(trigechoPin,LOW); //Set the trig pin Low

  pinMode(trigechoPin,INPUT);//Set the pin to input mode
  pulseWidthUs = pulseIn(trigechoPin,HIGH);//Detect the high level time on the echo pin, the output high level time represents the ultrasonic flight time (unit: us)

  distance = pulseWidthUs * VELOCITY_TEMP(20) / 2.0;//The distance can be calculated according to the flight time of ultrasonic wave,/
                                                    //and the ultrasonic sound speed can be compensated according to the actual ambient temperature
  Serial.print(distance, DEC);
  Serial.println("cm");
  delay(500);
}

Result

Result

Was this article helpful?

TOP