Example Code for Arduino-TRIG Pulse-triggered Mode
Last revision 2025/12/18
This example is the ultrasonic distance measurement of the module.
Hardware Preparation
- Name: Arduino Leonardo, Model/SKU: , Quantity: 1, Purchase Link: https://www.dfrobot.com/product-832.html
- Name: USB Data Cable, Model/SKU: , Quantity: 1, Purchase Link:
Software Preparation
- Development tools: Arduino IDE
Wiring Diagram

Other Preparation Work
- Ensure the sensor is in I2C mode and passive ranging mode(I2C Config register bit 2=1) before using.
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 21/08/2020
*/
#define VELOCITY_TEMP(temp) ( ( 331.5 + 0.6 * (float)( temp ) ) * 100 / 1000000.0 ) // The ultrasonic velocity (cm/us) compensated by temperature
int16_t trigPin = 5;
int16_t echoPin = 6;
uint16_t distance;
uint32_t pulseWidthUs;
void setup() {
Serial.begin(9600);
pinMode(trigPin,OUTPUT);
digitalWrite(trigPin,LOW);
pinMode(echoPin,INPUT);
delay(100);
}
void loop() {
int16_t dist, temp;
digitalWrite(trigPin,HIGH);//Set the tirgPin High
delayMicroseconds(50); //Delay of 50 microseconds
digitalWrite(trigPin,LOW); //Set the tirgPin Low
pulseWidthUs = pulseIn(echoPin,HIGH);//Measure echo high level time, the output high level time represents the ultrasonic flight time (unit: us)
distance = pulseWidthUs * VELOCITY_TEMP(33) / 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(100);
}
Result

Additional Information
-
Timing Diagram

Was this article helpful?
