KevsRobots Learning Platform
40% Percent Complete
By Kevin McAleer, 2 Minutes
Page last updated May 10, 2025
Your robot needs to be aware of its surroundings. With an ultrasonic sensor like the HC-SR04, you can measure the distance to objects and make your robot avoid collisions.
The HC-SR04 sends out a burst of ultrasound and listens for the echo. By measuring the time it takes for the echo to return, it can calculate distance.
Distance is calculated as:
distance (cm) = duration (Β΅s) / 58
Voltage divider for ECHO:
ECHO β 1kΞ© β Pico GP9
β
2kΞ©
β
GND
from machine import Pin, time_pulse_us
from time import sleep
trigger = Pin(8, Pin.OUT)
echo = Pin(9, Pin.IN)
def get_distance():
trigger.low()
sleep(0.002)
trigger.high()
sleep(0.01)
trigger.low()
duration = time_pulse_us(echo, 1, 30000) # timeout after 30ms
distance_cm = duration / 58
return distance_cm
while True:
dist = get_distance()
print("Distance:", dist, "cm")
sleep(0.5)
You can use the measured distance to decide what your robot should do:
distance = get_distance()
if distance < 10:
stop()
turn_right()
else:
forward()
Adjust the threshold to make your robot more or less cautious.
With obstacle detection working, your robot now reacts to the real world! Next up: Building a Two-Wheel Drive Robot
You can use the arrows β β
on your keyboard to navigate between lessons.