KevsRobots Learning Platform
By Kevin McAleer, 3 Minutes
In this lesson, you will learn:
Ultrasonic range finders measure distance by sending out a burst of high-frequency sound and timing how long the echo takes to come back. Robots use them to spot obstacles.
Sound travels at about 343 metres per second, or 0.0343cm per microsecond. The sound goes there and back, so:
distance (cm) = echo time (µs) x 0.0343 / 2 ≈ echo time / 58
VCC to VBUS (5V)GND to GNDTrig to GP2Echo to GP3 through a voltage divider (1kΩ from Echo to GP3, then 2kΩ from GP3 to GND)Protect the Pico
The standard HC-SR04 runs on 5V and its Echo pin outputs 5V, which is too much for a Pico input (see lesson 3). Use the divider, or buy the HC-SR04P, which works at 3.3V and can be powered from
3V3.
TrigEcho stays highfrom machine import Pin, time_pulse_us
from time import sleep, sleep_us
trig = Pin(2, Pin.OUT)
echo = Pin(3, Pin.IN)
def distance_cm():
trig.value(0)
sleep_us(2)
trig.value(1)
sleep_us(10)
trig.value(0)
duration = time_pulse_us(echo, 1, 30000) # give up after 30ms
if duration < 0:
return None # no echo: nothing in range
return duration / 58
while True:
d = distance_cm()
print("Out of range" if d is None else f"Distance: {d:.1f} cm")
sleep(0.5)
time_pulse_us() returns a negative number if no echo arrives before the timeout, so we check for that rather than printing a nonsense distance.
Combine this with lesson 6 so an LED lights up when something is closer than 20cm.
Quick quiz 1 of 2
Why do we divide by 58 (rather than 29) to get centimetres?
Quick quiz 2 of 2
Why does a standard HC-SR04’s Echo pin need a voltage divider?
You can use the arrows ← → on your keyboard to navigate between lessons.
Comments