from machine import Pin
import time
# Ultrasonic pins
trig = Pin(12, Pin.OUT)
echo = Pin(13, Pin.IN)
# LEDs
green = Pin(14, Pin.OUT)
yellow = Pin(27, Pin.OUT)
red = Pin(26, Pin.OUT)
def get_distance():
trig.value(0)
time.sleep_us(2)
trig.value(1)
time.sleep_us(10)
trig.value(0)
while echo.value() == 0:
start = time.ticks_us()
while echo.value() == 1:
end = time.ticks_us()
duration = time.ticks_diff(end, start)
dist = (duration * 0.0343) / 2 # cm
return dist
while True:
distance = get_distance()
print("Distance:", distance, "cm")
# Reset LEDs
green.value(0)
yellow.value(0)
red.value(0)
# Distance zones
if distance > 50:
green.value(1) # Safe
elif 20 <= distance <= 50:
yellow.value(1) # Caution
else:
red.value(1) # Danger
time.sleep(0.1)