Built-in project · Raspberry Pi 5

HC-SR04 distance sensor with gpiozero on a Raspberry Pi 5

gpiozero DistanceSensor on a Raspberry Pi 5: an HC-SR04 with its echo divided down to 3.3 V, the distance in the Serial Monitor and an LED inside 20 cm. The whole build, a Raspberry Pi 5 and 5 more parts, runs here in your browser on the Python below; open it in the editor to change the wiring or the code and run it again.

Teaching? Assign it to your class in one click.

Intermediate Runs in your browser. Free, and no account needed.

The parts retail for about $66. On Mokxi they're free.

HC-SR04 distance sensor with gpiozero · Raspberry Pi 5live0.000 s 0.00x
Click to open it in the editor
The circuit itself, running here on the simulator. Press what can be pressed; click anything else to open it in the editor.

The code

The Python exactly as the editor opens it. Change a line there and press Run: the board runs main.py in a Python engine in the page, with gpiozero and RPi.GPIO, and nothing to compile.

main.py · Raspberry Pi 5
# An HC-SR04 with gpiozero on a Raspberry Pi 5.
# TRIG on GPIO23 (pin 16). ECHO is a 5 V signal, so it reaches GPIO24 (pin 18)
# through a 1 k and 2 k divider: 5 V x 2/3 is 3.3 V, all a Pi's pin can take.
from gpiozero import DistanceSensor, LED
from time import sleep

sensor = DistanceSensor(echo=24, trigger=23, max_distance=2, threshold_distance=0.2)
led = LED(17)

sensor.when_in_range = led.on       # closer than 20 cm: the LED lights
sensor.when_out_of_range = led.off

while True:
    print(f"{sensor.distance * 100:.1f} cm")
    sleep(0.5)

Parts list

7 parts, plus the jumper wires. They retail for about $66; on Mokxi they're free.

How it is wired

9 connections, pin by pin, read from the circuit itself. Each line is one set of pins joined together, by a jumper wire or a breadboard strip.

  • Raspberry Pi 5 pin 5V; Ultrasonic ranger pin VCC
  • Ground: Raspberry Pi 5 pin GND; Ultrasonic ranger pin GND
  • Raspberry Pi 5 pin GPIO17; Resistor, 330 Ω pin 1
  • Ground: Raspberry Pi 5 pin GND; Resistor, 2k Ω pin 2
  • Raspberry Pi 5 pin GPIO23; Ultrasonic ranger pin TRIG
  • Raspberry Pi 5 pin GPIO24; Resistor, 1k Ω pin 2; Resistor, 2k Ω pin 1
  • Ground: Raspberry Pi 5 pin GND; LED, red pin C
  • Ultrasonic ranger pin ECHO; Resistor, 1k Ω pin 1
  • Resistor, 330 Ω pin 2; LED, red pin A

Change it and keep it

Open it in the editor, change the circuit or the code, and keep your version in a free account.