মূল বিষয়বস্তুতে যান
Learn/Sensing the world/Measuring distance with sound
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
Open in Lab
UNOATmega328P: The 8-bit AVR microcontroller that runs your sketch (16 MHz, 32 KB flash, 2 KB RAM).ATmega328PUSB-B: USB connection for uploading sketches and for the Serial Monitor. Also powers the board (5 V).DC jack: Barrel jack for 7–12 V from a battery pack or adapter (centre positive).ATmega16U2: Converts USB to serial for uploads and Serial.print().RESET: Restarts your sketch from the beginning (setup() runs again).L (D13): Built-in LED connected to pin 13 (LED_BUILTIN).ON: Power indicator.5 V regulator: Turns 7–12 V from VIN/jack into a steady 5 V.16 MHz: Clock source: the microcontroller runs 16 million cycles per second.ICSP: In-circuit programming header (SPI). Used to burn a bootloader; not needed for normal uploads.60 cm220 Ω+
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

1pulseIn returns 1160 µs. How far is the object?

2What does pulseIn() return when no echo arrives before the timeout?