Sensing the world · Lesson
12 min read
Measuring distance with sound
The HC-SR04 sends an ultrasonic ping and times the echo.
What You Will Learn
- Trigger a measurement
- Use pulseIn() to time the echo
- Convert time to centimetres
A 10 µs HIGH pulse on TRIG makes the sensor send 8 ultrasonic clicks. ECHO then stays HIGH until the echo returns. Sound travels about 343 m/s, so each centimetre to the object (there and back) takes about 58 µs.
Arduino C++
digitalWrite(TRIG, HIGH); delayMicroseconds(10); digitalWrite(TRIG, LOW); long us = pulseIn(ECHO, HIGH, 30000); long cm = us / 58;
Parking sensorarduino-uno
Note: Move the distance slider: the buzzer beeps faster as the 'car' gets closer.
The HC-SR04 needs 5 V and its ECHO pin outputs 5 V. On an ESP32 use a voltage divider on ECHO (1 kΩ + 2 kΩ).
Check Your Understanding
Test what you learned in this lesson