Measure distance with an ultrasonic sensor on the Raspberry Pi

Measure how far away things are with the HC-SR04 ultrasonic sensor and Python. You build a voltage divider so the sensor's 5 V signal can't harm the Pi, show the distance as a bar in the Shell, and light an...
  • Level:Beginner
  • Duration: 50 min
  • Ages 10+
  • Platform: Raspberry Pi
Measure distance with an ultrasonic sensor on the Raspberry Pi – EEMENTOR STEM™ lesson

Bats find their way in the dark by shouting and listening for the echo. The HC-SR04 ultrasonic sensor does the same: it sends out a short burst of sound far too high for you to hear, and times how long the echo takes to come back. The longer the wait, the further away the object. In this lesson you connect it to the Raspberry Pi, read the distance in centimetres with Python, and light a warning LED when something comes closer than 20 cm, like the parking sensor on a car. You also learn how to protect the Pi from a sensor that works at 5 V.

What you'll learn

  • How an ultrasonic sensor measures distance with an echo
  • Why the Pi's GPIO pins need protecting from 5 V signals
  • How a voltage divider turns 5 V into a safe 3.3 V
  • How to read distances with gpiozero's DistanceSensor and react when something is close

What you need

  • Raspberry Pi 4 Model B with Raspberry Pi OS on a microSD card (see the first lesson) and its USB-C power supply
  • Ultrasonic sensor HC-SR04 (ESP32 IoT Starter Kit)
  • 3 × 10 kΩ resistors, for the voltage divider (ESP32 IoT Starter Kit)
  • 1 LED and a 220 Ω resistor (ESP32 IoT Starter Kit)
  • Breadboard (ESP32 IoT Starter Kit)
  • Female-to-male jumper wires, to go from the Pi's pins to the breadboard. If you don't have any, plug a female-female and a male-male Dupont wire from the ESP32 IoT Starter Kit together.

Look after your Pi: the GPIO pins work at 3.3 V and are not 5 V tolerant. The HC-SR04 runs on 5 V, and its Echo pin sends back 5 V pulses, so Echo must never go straight to a GPIO pin: always through the voltage divider below. Never connect a 3V3 or 5V pin to GND, and always shut the Pi down and unplug it before you change the wiring.

Wiring

The sensor gets its power from the Pi's 5V pin. The Trig wire can go straight to a GPIO pin, because the Pi sends the signal and 3.3 V is enough to start a measurement. The Echo wire comes back at 5 V, so it goes through three 10 kΩ resistors in a row: one between Echo and the GPIO pin, two between the GPIO pin and GND. The pin then sees two thirds of 5 V, which is about 3.3 V.

Breadboard wiring diagram: HC-SR04 VCC to 5V (pin 2), Trig to GPIO 23 (pin 16), Echo through a 10 kilohm resistor to GPIO 24 (pin 18) with two more 10 kilohm resistors to GND, and a warning LED on GPIO 17 (pin 11).
Breadboard view. Check each connection against the wiring table below.
From To
HC-SR04 VCC 5V (pin 2)
HC-SR04 GND The blue (−) rail
HC-SR04 Trig GPIO 23 (pin 16)
HC-SR04 Echo 10 kΩ resistor (R1) → the divider point
The divider point GPIO 24 (pin 18), and 10 kΩ (R2) → 10 kΩ (R3) → the blue (−) rail
GPIO 17 (pin 11) 220 Ω resistor → LED long leg (+); LED short leg (−) → the blue (−) rail
The blue (−) rail GND (pin 9)

The program

Open Thonny (Raspberry menu → Programming → Thonny), paste the program into a new file, save it in your home folder as distance.py, and click the green Run button. Press the red Stop button (or Ctrl+C) to stop it. gpiozero is already installed on Raspberry Pi OS.

# Measure distance with an HC-SR04 on the Raspberry Pi (gpiozero)
from gpiozero import DistanceSensor, LED
from time import sleep

# Echo goes through the voltage divider to GPIO 24. Never connect it directly.
sensor = DistanceSensor(echo=24, trigger=23, max_distance=2, threshold_distance=0.2)
warning = LED(17)

sensor.when_in_range = warning.on       # something closer than 20 cm
sensor.when_out_of_range = warning.off

while True:
    cm = sensor.distance * 100          # distance is in metres (0 to 2)
    bar = "#" * int(cm / 5)             # one # for every 5 cm
    print(f"{cm:6.1f} cm  {bar}")
    sleep(0.2)

Try it

  1. Run the program and point the sensor at the ceiling or a wall. The Shell prints the distance five times a second.
  2. Hold your hand in front of the sensor and move it slowly away. The number and the bar grow together.
  3. Bring your hand closer than 20 cm: the LED lights up. Move it back and the LED goes off.
  4. Check it with a ruler: put a book exactly 30 cm away and see how close the reading is.
  5. Change threshold_distance=0.2 to 0.5 to make the warning start at 50 cm.

What you should see

Thonny Shell output of distance.py: distances in centimetres with a bar of hash signs, the LED switching on below 20 cm and off again.
The bar grows as your hand moves away.

How it works

How the HC-SR04 works: sound out and echo back, the Trig pulse and the Echo pulse whose length is the travel time, and the three 10 kilohm resistors that turn 5 V into 3.3 V for GPIO 24.
Timing the echo, and the voltage divider that protects the Pi.

When the Pi sends a pulse of at least 10 microseconds to Trig, the sensor sends eight pulses of 40 kHz sound. Then it sets Echo high and keeps it high until the echo comes back. The time Echo stays high is the time the sound needs to go to the object and back. Sound travels about 340 metres per second, so the distance is that time × 340 m/s ÷ 2 (÷ 2 because the sound goes there and back). DistanceSensor does all of this for you and gives the answer in metres.

The voltage divider works like sharing out the voltage. The three resistors are the same size, so each one gets a third of the 5 V. GPIO 24 sits above the bottom two, so it sees two thirds: 5 V × 20 kΩ ÷ 30 kΩ ≈ 3.3 V, which is safe for the Pi and still counts as "high".

threshold_distance=0.2 tells gpiozero what "in range" means: closer than 0.2 m. Every time the distance crosses that line, it calls warning.on or warning.off for you, while the loop keeps printing.

Try this next

  • Turn it into a parking sensor: make the LED blink faster the closer you get, with warning.blink(on_time=..., off_time=...).
  • Add the buzzer from the ESP32 kit and beep when something is within 10 cm.
  • Measure the length of a room by pointing the sensor from one wall to the other (change max_distance to 4).
  • Next lesson: build a motion alarm that logs every visit.

Troubleshooting

  • The distance is always 200 cm, or the Shell shows a "no echo received" warning: the echo never arrives. Check the Echo wire and the divider: R1 from Echo to the divider point, GPIO 24 on the divider point, R2 and R3 down to GND. Also check that VCC is on 5V, not 3V3.
  • The distance is always 0: Trig and Echo are swapped. Trig goes to GPIO 23, Echo (through the divider) to GPIO 24.
  • The numbers jump around by a centimetre or two: that is normal for this sensor and for timing on a computer like the Pi. Soft things like curtains and clothes reflect sound badly, so aim at a flat, hard surface.
  • Readings under 2 cm are wrong: the HC-SR04 can't measure that close. It works from about 2 cm to 4 m.
  • Always shut down properly: click the Raspberry menu → Shutdown, or type sudo shutdown now, and wait until the green light stops flashing before you unplug the power.