Ultrasonic distance meter
Measure distance with an HC-SR04 by timing an ultrasonic echo with pulseIn().
Sensors · Beginner
In a real product: Car parking sensor (Automotive): Measures the distance to obstacles.
The HC-SR04 sends a burst of ultrasound and listens for the echo, like a bat. The time the echo takes to come back, times the speed of sound, is twice the distance to the object.
What you'll learn
- Sending a trigger pulse with
delayMicroseconds() - Measuring a pulse's length with
pulseIn() - Converting a time to a distance using the speed of sound
How it works
A 10 µs HIGH pulse on TRIG (pin 3) starts a measurement. The sensor then sets ECHO (pin 2) HIGH for as long as the sound took to go out and back.
Sound travels about 343 m/s, or 0.0343 cm/µs. The echo covers the distance twice, so distance = time × 0.0343 / 2, which is the same as time / 58. pulseIn(ECHO, HIGH, 30000) waits for the pulse and returns its length in microseconds, or 0 if nothing came back within 30 ms (out of range).
Closer than 20 cm, the built-in LED lights as a warning.
Try this
- Change the sensor's distance slider while it runs.
- Make a parking sensor: beep faster as the distance drops.
- Average five readings to smooth out noise.
sketch.ino
// An HC-SR04 ultrasonic sensor: TRIG on pin 3, ECHO on pin 2. Prints the distance in cm.
const int TRIG = 3;
const int ECHO = 2;
void setup() {
pinMode(TRIG, OUTPUT);
pinMode(ECHO, INPUT);
pinMode(LED_BUILTIN, OUTPUT);
Serial.begin(9600);
}
void loop() {
// A 10 us pulse on TRIG starts a measurement.
digitalWrite(TRIG, LOW);
delayMicroseconds(2);
digitalWrite(TRIG, HIGH);
delayMicroseconds(10);
digitalWrite(TRIG, LOW);
long echoUs = pulseIn(ECHO, HIGH, 30000); // 0 if no echo within 30 ms
if (echoUs == 0) {
Serial.println("Out of range");
} else {
float cm = echoUs / 58.0; // there and back at 343 m/s
Serial.print("Distance: ");
Serial.print(cm, 1);
Serial.println(" cm");
digitalWrite(LED_BUILTIN, cm < 20 ? HIGH : LOW);
}
delay(500);
}