Raspberry Pi Ultrasonic Sensor
Ultrasonic distance sensors like the HC-SR04 measure how far away an object is by timing how long a burst of sound takes to bounce back, and gpiozero's DistanceSensor class turns that timing into a distance for you.
Distance from a Sound's Round Trip
An ultrasonic sensor emits a short burst of sound above the range of human hearing - typically around 40kHz - and listens for it to bounce off whatever is in front of it. Sound travels through air at a fairly predictable speed, roughly 343 metres per second at room temperature, so if you know how long the burst took to leave the sensor and return, you can calculate distance directly: distance equals speed of sound multiplied by elapsed time, divided by two because the sound travelled the gap twice - out to the object and back.
Trigger and Echo: A Two-Pin Handshake
The HC-SR04 splits this into two separate pins. TRIG is an input to the sensor - the Pi sends it a brief 10 microsecond high pulse to say 'take a reading now'. ECHO is an output from the sensor - it goes high the instant the sound burst is sent and stays high until the echo is detected, so the duration of that high pulse on ECHO is exactly the round-trip time you need.
- VCC to 5V and GND to a Pi ground pin.
- TRIG to any GPIO pin configured as an output - 3.3V logic is fine here since the Pi is driving it.
- ECHO to a GPIO pin through a voltage divider, since the HC-SR04 drives ECHO at 5V, which exceeds the 3.3V a Pi input pin is rated for.
- gpiozero's DistanceSensor(echo=..., trigger=...) handles sending the trigger pulse and timing the echo pulse for you.
Example
from gpiozero import DistanceSensor
sensor = DistanceSensor(echo=24, trigger=23)
print(f'Distance: {sensor.distance * 100:.1f} cm')Example
from gpiozero import DistanceSensor, LED
from time import sleep
sensor = DistanceSensor(echo=24, trigger=23, max_distance=2)
warning = LED(17)
while True:
distance_cm = sensor.distance * 100
warning.value = distance_cm < 15 # light up when something is close
print(f'{distance_cm:.1f} cm')
sleep(0.2)