Sensing the world · Lesson 1 of 5· 18 min
Measuring distance with sound
Why this matters
Many useful machines need to know how far away something is: a water level, a car reversing, a door that opens for people. An ultrasonic sensor measures distance with sound too high for people to hear.
How it works
The sensor sends a short click of sound and listens for the echo. Sound travels about 343 metres per second, so the time until the echo tells you the distance. For centimetres, divide the echo time in microseconds by 58.
Open a tool
Wokwi simulator
Free, nothing to install. Works best on a laptop; on a phone you can still read the steps and the code below.
Opens wokwi.com in a new tab. Come back here when you are done.
Step by step
-
Press Open Wokwi simulator above to start a new Pico project.
-
Add an HC-SR04 ultrasonic sensor.
-
Wire VCC to VBUS, GND to GND, TRIG to GP3 and ECHO to GP2.
from machine import Pin, time_pulse_us
import time
trig = Pin(3, Pin.OUT)
echo = Pin(2, Pin.IN)
def distance_cm():
trig.value(0)
time.sleep_us(2)
trig.value(1) # a 10 microsecond click
time.sleep_us(10)
trig.value(0)
t = time_pulse_us(echo, 1, 30000) # how long the echo lasted
if t < 0:
return None # no echo came back
return t / 58
while True:
print(distance_cm())
time.sleep(0.5)
Run it, then click the sensor in the simulator and move its distance slider. The readings follow.
Your task
Read the distance at three slider positions and write them down. Do the numbers match what the slider says? Real sensors are a little off; that is normal.