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.

Open Wokwi simulator

Step by step

  1. Press Open Wokwi simulator above to start a new Pico project.

  2. Add an HC-SR04 ultrasonic sensor.

  3. 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.

You’re reading for free. Sign in to save your progress, ask questions on any lesson, and earn a certificate when you finish.Sign in to keep my progress →

Lesson 1 of 5