PyRaspBeta

Distance sensor module (3.3 V safe)

The distance module is an HC-SR04 ultrasonic ranger with the 1 kΩ and 2 kΩ resistors that form the ECHO voltage divider already fitted, so the sensor's 5 V echo arrives at about 3.3 V. It costs $5.50 and is for distance sense: parking, level detection, presence, a robot's eyes. Wire vcc to 5 V, trig and echo to GPIOs and gnd to ground.

What's inside

PartQtyPrice each
HC-SR04 distance sensor1$3
Resistor2$0.25
Total3$3.50
  • The HC-SR04 pings at 40 kHz and reports the round-trip echo time; it needs a 5 V supply and outputs a 5 V echo.
  • The 1 kΩ resistor is the top of the divider from ECHO, and the 2 kΩ resistor the bottom to ground — together they scale 5 V down to 3.33 V, a safe level for a GPIO.
Exposed pinInside the kit
vccsonar:VCC
trigsonar:TRIG
echor1:2
gndsonar:GND

echo is the junction between the two resistors, not the raw ECHO pin, which is what makes the module 3.3 V safe. vcc must be 5 V; trig is a plain 3.3 V input. The kit has no chain ends.

Wiring it in circuit.py

circuit.py
from wiring import *

pi = Pi()
sonar = kits.DistanceModule()

pi.V5 >> sonar.vcc        # the HC-SR04 is a 5 V part
pi.GPIO23 >> sonar.trig
pi.GPIO24 >> sonar.echo   # divided to 3.3 V inside the kit
sonar.gnd >> pi.GND

Driving it in main.py

main.py
from gpiozero import DistanceSensor
from time import sleep

sonar = DistanceSensor(echo=24, trigger=23, max_distance=4)

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

Why buy the kit

Loose parts cost $3 + 2 × $0.25 = $3.50, against $5.50 — $2.00 for the divider fitted. That $2.00 is cheap insurance: feeding the raw 5 V echo into a GPIO is the HC-SR04's classic way to damage a Pi, and the module's divider ratio is already right. Building it by hand means choosing the two resistor values and remembering which one is the top half.

Simulator vs real hardware

  • gpiozero.DistanceSensor works unmodified: the simulator times the echo with the clock readings of the edges, so distances come out right even though the simulation advances in steps.
  • The speed of sound follows the zone temperature (~1.8 % faster at 30 °C than at 0 °C), and a ping that finds nothing in range gives a 38 ms echo, which the sensor reports as its maximum distance; leave at least 60 ms between pings, which sleep(0.5) comfortably does.
  • The datafeed's "missed echo" knob and the object's distance simulate angled and soft surfaces; the divider itself is exact, so there is no 5 V on the GPIO to detect.

Further reading