By Kevin McAleer, 8 Minutes
Page last updated November 21, 2026

Time to use the whole toolbox on one job. You’ll write a small driver, a module that hides the fiddly details of a piece of hardware behind a friendly function, and take it from first draft to something you’d be happy to share.
The hardware is the HC-SR04 ultrasonic range finder, the sensor on the front of the robot from Wire It Up. You don’t need one to follow along.
The HC-SR04 measures distance with sound, like a bat.
Sound travels about 343 metres a second, and it goes there and back, so:
# duration is in microseconds
# 343 m/s is 0.343 mm per microsecond, halved for the round trip
distance_mm = duration * 343 // 2000
obstacle-robot and open it in Snakie with Open Folderhcsr04.pyStarting Git first means every later step leaves a trail.
Type this in. Lean on autocomplete: from machine import then Ctrl+Space will find time_pulse_us for you, and typing time_pulse_us( shows what it wants.
from machine import Pin, time_pulse_us
import time
class HCSR04:
"""Driver for the HC-SR04 ultrasonic range finder."""
def __init__(self, trigger, echo, timeout_us=30000):
self.trigger = Pin(trigger, Pin.OUT)
self.echo = Pin(echo, Pin.IN)
self.timeout_us = timeout_us
self.trigger.value(0)
def _pulse(self):
self.trigger.value(1)
time.sleep_us(10)
self.trigger.value(0)
return time_pulse_us(self.echo, 1, self.timeout_us)
def distance_mm(self):
"""Return the distance in millimetres, or -1 if nothing was heard."""
duration = self._pulse()
if duration < 0:
return -1
return duration * 343 // 2000
A few things to notice:
_pulse starts with an underscore. That’s Python’s way of saying this is for the class’s own usetime_pulse_us returns a negative number if no echo arrives in time, so distance_mm returns -1 to mean nothing heard// 2000 is integer division. No floats, so no memory allocated on every readingHover over time_pulse_us to read its documentation, and use Help for symbol on Pin if you want a reminder of Pin.OUT and Pin.IN.
Click Problems. With ruff installed you may see an import-order note. Fix anything marked ⚠ first.
Now deliberately break it: change one self.echo to self.ecko. Notice that nothing complains, because an attribute on self can’t be checked without running the code. Change duration to duraton in the if instead, and an undefined name finding appears at once. Linters are powerful, and they have limits. Put both back.
Commit: Add HC-SR04 driver.
Create main.py. This first version is written the way most of us would write it on day one.
from machine import Pin, PWM
import time
from hcsr04 import HCSR04
LEFT_MOTOR_PIN = 10
RIGHT_MOTOR_PIN = 12
TOO_CLOSE_MM = 200
sensor = HCSR04(trigger=14, echo=15)
left = PWM(Pin(LEFT_MOTOR_PIN))
right = PWM(Pin(RIGHT_MOTOR_PIN))
def drive(speed):
duty = int(speed * 65535 / 100)
left.duty_u16(duty)
right.duty_u16(duty)
while True:
distance = sensor.distance_mm()
if distance < TOO_CLOSE_MM:
drive(0)
else:
drive(60)
time.sleep(0.1)
Commit it as it is: First version of main. A working-but-rough commit is exactly what you want before tidying.
Open Problems. This is the file from lesson 4, and it has six hints.
const() and sleep_ms hints have gone. Then make the // change on the duty line, from the lightbulb if one is offered or by handmain.py. Read the diff. Every change Tidy made is there in red and greenTidy main with const and integer mathsOne hint is left: This loop blocks for 100 ms every pass. There’s no lightbulb, so this one is yours.
time.sleep_ms(100) makes the robot deaf for a tenth of a second, every loop. Nothing else can happen in that time: no button check, no second sensor, no LED blink.
The fix is to ask “has 100 ms passed yet?” instead of waiting for it. Here’s the finished program. So that it runs on this page, a small FakeSensor class stands in for the real driver and the loop stops after six readings.
The important lines:
now = time.ticks_ms()
if time.ticks_diff(now, last_check) >= _CHECK_EVERY_MS:
last_check = now
ticks_ms() is a millisecond counter. ticks_diff() subtracts two readings safely, even when the counter wraps round to zero, which it eventually does. Always use it, never a plain minus.
The constants now begin with an underscore, as in _TOO_CLOSE_MM = const(200). The const() help article from lesson 5 explains why: with the underscore, the name doesn’t even take up space in memory.
For the real robot, delete the FakeSensor class, bring back from hcsr04 import HCSR04 and sensor = HCSR04(trigger=14, echo=15), and change the loop to while True:.
Check Problems once more. Snakie now points at the print calls inside the loop: printing is slow, and on a finished robot you’d switch it off. A new hint for a new version. That’s the tool doing its job.
Commit: Make the main loop non-blocking.
The driver is finished and stable. main.py will keep changing. So:
hcsr04.py and choose Compile to .mpyhcsr04.mpy and check DEFINES lists HCSR04 with its three methodshcsr04.mpy and main.py to the board, not hcsr04.pyKeep hcsr04.py in Git. It’s the source, and you’ll need it to recompile after a firmware update.
| File | In Git? | On the board? |
|---|---|---|
main.py |
Yes | Yes |
hcsr04.py |
Yes | No |
hcsr04.mpy |
Your choice | Yes |
.gitignore |
Yes | No |
And a history of four commits that tells the story of how it got there.
distance_cm() method to the driver that uses distance_mm(). Recompile and check it appears under DEFINES.last_blink variable.DEBUG = False flag and only print when it’s true. Does the hint go away?Problem: distance_mm() always returns -1 on real hardware.
Solution: Check Trigger and Echo aren’t swapped, and that the sensor has power and ground.
Why: -1 means no echo pulse arrived before the timeout.
Problem: ImportError: no module named 'hcsr04'.
Solution: Upload hcsr04.mpy (or hcsr04.py) to the board, next to main.py or in /lib.
Why: main.py imports the driver from the board’s own file system.
Problem: ImportError: can't import name time_pulse_us on the simulated device.
Solution: Use the FakeSensor version on the simulator, and the real driver on a board.
Why: The simulator doesn’t have that hardware timing function.
Quick quiz 1 of 3
Why commit the rough first version before tidying?
Quick quiz 2 of 3
Why use time.ticks_diff() instead of subtracting?
Quick quiz 3 of 3
Which file do you compile to .mpy in this project?
You can use the arrows ← → on your keyboard to navigate between lessons.
Comments