Measure distance to an object using an HC-SR04 ultrasonic sensor, by manually timing how long a sound pulse takes to bounce back.
time.ticks_us()The HC-SR04 integrates both an ultrasonic transmitter and receiver. The transmitter turns an electrical pulse into a high-frequency sound wave (above human hearing); the receiver listens for that wave bouncing back off an obstacle.

| Pin | Description |
|---|---|
| VCC | Power supply (5V) |
| Trig | Trigger pin — sends the pulse |
| Echo | Echo pin — outputs how long the pulse took to return |
| GND | Ground |
To take a reading: hold Trig HIGH for at least 10µs to fire a pulse. Echo then goes HIGH for as long as the sound is in flight, and goes LOW the instant the echo is received. Since sound travels at a constant ~340m/s, timing that HIGH duration gives the round-trip distance: distance = speed × time / 2 (divided by 2 because the sound travels to the object and back).

The HC-SR04 runs on 5V, not 3.3V — make sure VCC is wired to the 5V rail.
Disconnect all power before building the circuit. Reconnect once verified.

Connections:

File: 03_sensors/code/Ultrasonic_Ranging.py
from machine import Pin
import time
trigPin=Pin(13,Pin.OUT,0)
echoPin=Pin(14,Pin.IN,0)
soundVelocity=340
distance=0
def getSonar():
trigPin.value(1)
time.sleep_us(10)
trigPin.value(0)
while not echoPin.value():
pass
pingStart=time.ticks_us()
while echoPin.value():
pass
pingStop=time.ticks_us()
pingTime=time.ticks_diff(pingStop,pingStart)
distance=pingTime*soundVelocity//2//10000
return int(distance)
time.sleep_ms(2000)
while True:
time.sleep_ms(500)
print('Distance: ',getSonar(),'cm' )
03_sensors/code/.Ultrasonic_Ranging.py.trigPin.value(1)
time.sleep_us(10)
trigPin.value(0)
Holds Trig HIGH for 10 microseconds, telling the HC-SR04 to send an ultrasonic pulse.
while not echoPin.value():
pass
pingStart=time.ticks_us()
while echoPin.value():
pass
pingStop=time.ticks_us()
pingTime=time.ticks_diff(pingStop,pingStart)
Waits for Echo to go HIGH (the pulse has been sent), records the start time, then waits for it to go LOW again (the echo was received) and records the stop time. time.ticks_diff() safely computes the elapsed microseconds even if the internal tick counter has wrapped around.
distance=pingTime*soundVelocity//2//10000
soundVelocity is in m/s; dividing by 2 accounts for the round trip, and //10000 converts the units down to centimeters (since pingTime is in microseconds and velocity is in m/s).
time.ticks_us() / time.ticks_diff(): MicroPython’s safe way to measure short, precise time intervals (handles counter rollover, unlike subtracting raw values)while not echoPin.value(): pass): block execution until a pin changes state — simple, but ties up the CPU while waitingNone if getSonar() waits too long (the object may be out of range).Adapted from Python_Tutorial.pdf Project 21.1