from machine import Pin, PWM, time_pulse_us
from time import sleep
# Pines del sensor ultrasónico
TRIG = Pin(3, Pin.OUT)
ECHO = Pin(4, Pin.IN)
# Pines de los LEDs
led_verde = Pin(14, Pin.OUT)
led_amarillo = Pin(15, Pin.OUT)
led_rojo = Pin(13, Pin.OUT)
# Buzzer en GP12
buzzer = PWM(Pin(12))
buzzer.freq(2000)
buzzer.duty_u16(0) # apagado al inicio
def medir_distancia():
TRIG.low()
sleep(0.0002)
TRIG.high()
sleep(0.00001)
TRIG.low()
duracion = time_pulse_us(ECHO, 1, 30000)
if duracion < 0:
return None
distancia = (duracion / 2) * 0.0343
return distancia
def apagar_leds():
led_verde.low()
led_amarillo.low()
led_rojo.low()
def beep(velocidad):
if velocidad <= 0:
buzzer.duty_u16(0)
return
buzzer.duty_u16(20000)
sleep(velocidad)
buzzer.duty_u16(0)
sleep(velocidad)
while True:
d = medir_distancia()
if d is None:
apagar_leds()
buzzer.duty_u16(0)
continue
print("Distancia:", d, "cm")
if d > 40:
apagar_leds()
buzzer.duty_u16(0)
elif 25 < d <= 40:
led_verde.high()
led_amarillo.low()
led_rojo.low()
beep(0.4) # pitido lento
elif 10 < d <= 25:
led_verde.high()
led_amarillo.high()
led_rojo.low()
beep(0.2) # pitido medio
elif d <= 10:
led_verde.high()
led_amarillo.high()
led_rojo.high()
beep(0.05) # pitidos rápidos