from machine import Pin, PWM
from utime import sleep_us, ticks_us, sleep
red_pin = Pin(23, Pin.OUT)
yellow_pin = Pin(22, Pin.OUT)
green_pin = Pin(19, Pin.OUT)
trigger = Pin(25, Pin.OUT)
echo = Pin(33, Pin.IN)
def ultra():
trigger.off()
sleep_us(2)
trigger.on()
sleep_us(5)
trigger.off()
while echo.value() == 0:
signal_off = ticks_us()
while echo.value() == 1:
signal_on = ticks_us()
try:
time_pass = signal_on - signal_off
except NameError:
return 0
return time_pass/58
while True:
dist = ultra()
print(f'Distance: {dist:.1f}cm')
sleep(0.1)
if dist <=50:
buzzer=PWM(Pin(27),freq=1000,duty=512)
red_pin.on()
yellow_pin.off()
red_pin.off()
elif dist <=100:
buzzer=PWM(Pin(27),freq=600,duty=512)
red_pin.off()
green_pin.off()
yellow_pin.on()
elif dist <=200:
buzzer=PWM(Pin(27),freq=300,duty=0)
yellow_pin.off()
red_pin.off()
green_pin.on()
else:
buzzer=PWM(Pin(27),freq=100,duty=0)
yellow_pin.off()
red_pin.off()
green_pin.off()