Built-in project · Raspberry Pi Pico

MicroPython HC-SR04 on a Pico with a driver module

MicroPython on a Raspberry Pi Pico: an HC-SR04 on GP19 and GP18, read through a small hcsr04.py driver, 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.

Intermediate About 15 minutes to build and run. Runs in your browser. Free, and no account needed.

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

The circuit runs here once the page has loaded.

What you'll learn

  • Measuring distance with sound
  • Dividing a 5 V signal down for a 3.3 V pin
  • Putting hardware code in a driver file
  • Turning echo time into centimeters
  • Difficulty: Intermediate
  • Time: About 15 minutes
  • Board: Raspberry Pi Pico
  • Parts: 5

How it works

An HC-SR04 ultrasonic ranger measures distance. The Pico sends a short pulse on TRIG (GP19), and the ranger sends out a burst of sound. ECHO stays high for as long as the sound takes to go out and come back.

ECHO is a 5 V signal, so it passes through a 1k and 2k resistor divider before it reaches GP18. That keeps the Pico pin safe.

A helper file, hcsr04.py, does the trigger and timing. The main loop only asks for the distance and prints it every 500 ms. If no echo comes back, it prints "nothing in range".

Parts list

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

Kits that can build it

This starter kit has every part in the circuit. Each kit's page lists what else it can build.

Wiring table

Every connection, pin by pin, read from the circuit itself. Each row joins the pin on the left to the pin on the right, by a jumper wire or a breadboard strip.

Part and pinConnects to
Ultrasonic ranger pin TRIGRaspberry Pi Pico pin GP19
Resistor, 1k Ω pin 2Raspberry Pi Pico pin GP18
Resistor, 2k Ω pin 1Raspberry Pi Pico pin GP18
Ultrasonic ranger pin VCC5 V
Resistor, 1k Ω pin 1Ultrasonic ranger pin ECHO
Ultrasonic ranger pin GNDGround
Resistor, 2k Ω pin 2Ground

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.

main.py · Raspberry Pi Pico
# The same ranger with a driver: hcsr04.py, in the next tab, does the
# trigger and the timing, so the loop only asks for the distance.
import time
from hcsr04 import HCSR04

sonar = HCSR04(trig=19, echo=18)

while True:
    d = sonar.distance_cm()
    print("distance: %.1f cm" % d if d is not None else "nothing in range")
    time.sleep_ms(500)
hcsr04.py · Raspberry Pi Pico
# hcsr04.py: an HC-SR04 ultrasonic ranger.
# A 20 us pulse on TRIG sends a burst of sound; ECHO stays high for as long
# as the sound took to get there and back.
from machine import Pin, time_pulse_us
import time

class HCSR04:
    def __init__(self, trig, echo):
        self.trig = Pin(trig, Pin.OUT, value=0)
        self.echo = Pin(echo, Pin.IN)

    def distance_cm(self):
        self.trig.value(1)
        time.sleep_us(20)                         # 20 us: the datasheet asks for at least 10
        self.trig.value(0)
        us = time_pulse_us(self.echo, 1, 30000)   # 30 ms is about 5 m
        if us < 0:
            return None                           # no echo: nothing in range
        return us * 0.0343 / 2                    # sound: 343 m/s, there and back

Troubleshooting

The usual mistakes with this circuit, and the fix for each.

  • The Pico pin gets 5 V from ECHO. This project
    ECHO must go through the 1k resistor, with the 2k resistor from that point to ground, before it reaches GP18.
  • It always says "nothing in range". This project
    Check TRIG is on GP19 and ECHO reaches GP18 through the divider. Check the ranger has 5 V and ground.
  • Distance reads zero, or never changes. Ultrasonic ranger
    Power it from 5 V and share ground. Send a 10 microsecond HIGH pulse on TRIG, then time ECHO with pulseIn. Check TRIG and ECHO are not swapped.
  • Readings jump around or are wrong on a 3.3 V board. Ultrasonic ranger
    ECHO outputs 5 V, so divide it down for 3.3 V boards. Aim at flat, hard surfaces. The range is about 2 cm to 4 m, and soft or angled targets bounce the sound away.
  • The LED is dim, burns out, or the pin reads wrong because the resistor value is off. Resistor
    Read the color bands again. A 220 ohm to 330 ohm resistor suits a typical LED on 5 V. 10k is a common pull-up or pull-down value. Check with a multimeter if unsure.
  • A pull-up or pull-down resistor is missing, so the input floats and reads random values. Resistor
    Tie the input to 5 V or ground through about 10k. Or use INPUT_PULLUP and wire the switch to ground.
  • The Pico does not show up as a drive, or the program will not load. Raspberry Pi Pico
    Hold the BOOTSEL button while you plug in USB. A drive named RPI-RP2 appears. Then copy the UF2 file onto it.
  • A 5 V signal or sensor is wired to a GPIO pin. Raspberry Pi Pico
    Pico GPIO pins are 3.3 V only and are not 5 V tolerant. Use a level shifter or a voltage divider for any 5 V output going into the board.

Change it and keep it

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