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)
Note: Never connect the HC-SR04's ECHO pin directly to a GPIO input. It outputs 5V logic, and a Raspberry Pi's GPIO pins are only rated for 3.3V - a simple two-resistor voltage divider (for example 1k ohm and 2k ohm) brings it down to a safe level.
SpecTypical HC-SR04 value
RangeAbout 2cm to 400cm
Beam angleAbout 15 degrees
ResolutionAbout 0.3cm
Recommended gap between readings60ms or more, to let the previous echo fully die out
Note: DistanceSensor already averages several readings internally (controlled by its queue_len argument) to smooth out noise, and the distance property is reported in metres, capped at whatever max_distance you configure - readings beyond that are simply reported as max_distance rather than left unmeasured.
Note: The speed of sound actually changes slightly with air temperature, so extremely precise applications compensate for it. For hobby robotics and typical indoor projects the fixed 343 m/s assumption gpiozero uses is accurate enough that you will not notice the difference.