HC-SR04 on a Pico with MicroPython
MicroPython on a Raspberry Pi Pico: machine.time_pulse_us() times an HC-SR04’s echo, divided down to 3.3 V, and prints the distance twice a second. The whole build, a Raspberry Pi Pico and 3 more parts, runs here in your browser on the firmware 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.
Beginner Runs in your browser. Free, and no account needed.
The parts retail for about $10.10. On Mokxi they're free.
The code
The MicroPython code exactly as the editor opens it. Change a line there and press Run: the board runs it on the official MicroPython firmware, with nothing to compile.
# An HC-SR04 on a Raspberry Pi Pico, in MicroPython.
# The HC-SR04 needs 5 V, from VBUS (pin 40). TRIG is on GP3 (pin 5). ECHO is a
# 5 V pulse, so it reaches GP2 (pin 4) through a 1 k and 2 k divider: 5 V x 2/3
# is 3.3 V, all the RP2040 can take.
from machine import Pin, time_pulse_us
import time
trig = Pin(3, Pin.OUT)
echo = Pin(2, Pin.IN)
led = Pin("LED", Pin.OUT) # the Pico's own LED: lit closer than 20 cm
def distance_cm():
trig.low()
time.sleep_us(2)
trig.high()
time.sleep_us(10) # a 10 us pulse starts a measurement
trig.low()
t = time_pulse_us(echo, 1, 30000) # how long ECHO stays high, in us
if t < 0:
return None # no echo within 30 ms: nothing in range
return t * 0.0343 / 2 # sound goes 0.0343 cm a microsecond, there and back
while True:
d = distance_cm()
if d is None:
print("Out of range")
else:
print("Distance: %.1f cm" % d)
led.value(d < 20)
time.sleep(0.5)
Parts list
5 parts, plus the jumper wires. They retail for about $10.10; on Mokxi they're free.
- 1 × Raspberry Pi Pico
- 1 × Half breadboard
- 1 × Ultrasonic ranger
- 1 × Resistor, 1k Ω
- 1 × Resistor, 2k Ω
How it is wired
6 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.
- Ground: Raspberry Pi Pico pin GND; Ultrasonic ranger pin GND
- Raspberry Pi Pico pin GP2; Resistor, 1k Ω pin 2; Resistor, 2k Ω pin 1
- Raspberry Pi Pico pin GP3; Ultrasonic ranger pin TRIG
- Ground: Raspberry Pi Pico pin GND; Resistor, 2k Ω pin 2
- Raspberry Pi Pico pin VBUS; Ultrasonic ranger pin VCC
- Ultrasonic ranger pin ECHO; Resistor, 1k Ω pin 1
Change it and keep it
Open it in the editor, change the circuit or the code, and keep your version in a free account.