from machine import Pin, time_pulse_us
import utime
# Change these if you wired the sensor to different GPIOs
TRIG_PIN = 3
ECHO_PIN = 2
trig = Pin(TRIG_PIN, Pin.OUT)
echo = Pin(ECHO_PIN, Pin.IN)
SOUND_SPEED = 343 # metres per second (20 °C, sea-level)
MAX_DIST_CM = 500 # ≈5 m max range you care about
TIMEOUT_US = int((MAX_DIST_CM / 100) * 2 / SOUND_SPEED * 1_000_000)
def distance_cm() -> float | None:
"""Return distance in centimetres, or None on timeout."""
# 1 ) Make sure the trigger is LOW for ≥2 µs
trig.value(0)
utime.sleep_us(2)
# 2 ) Send a 10 µs HIGH pulse to start measurement
trig.value(1)
utime.sleep_us(10)
trig.value(0)
# 3 ) Measure echo HIGH pulse width (µs)
try:
pulse_len = time_pulse_us(echo, 1, TIMEOUT_US)
except OSError: # time_pulse_us timed out
return None
# 4 ) Distance = (pulse time × speed of sound) / 2
return (pulse_len * SOUND_SPEED / 1_000_000) * 100 / 2 # → centimetres
# ────────────────────────────── MAIN LOOP ────────────────────────────── #
while True:
dist = distance_cm()
if dist is None:
print("Out of range or no echo")
else:
print("Distance: {:.2f} cm".format(dist))
utime.sleep(1)