2 · Inputs & sensors
Ultrasonic range finder (HC-SR04)
Advanced20 min
Goal
Measure a distance in centimetres with an ultrasonic sensor.
Why it matters
You measure a time of flight: distance = (duration × 340 m/s) / 2, exactly like a radar.
Steps
- 01Add the ultrasonic sensor (TRIG on 9, ECHO on 10).
- 02Send a 10 µs pulse on TRIG.
- 03Measure the echo duration with pulseIn(ECHO, HIGH).
- 04Convert: cm = duration / 58.
This tutorial runs inside the Circuitly simulator: your wiring and your code are checked automatically at every step.
Next tutorials
- Read a push button
Light the LED only while the button is pressed.
- Toggle button (debounced)
One press turns on, the next turns off — with no contact bounce.
- Read a potentiometer
Print the analog value of A0 on the serial monitor.
- Convert to volts (map & float)
Turn the ADC's 0–1023 into a 0.00–5.00 V reading.