from machine import Pin, time_pulse_us
import time
# Definir pines
TRIG_PIN = 19
ECHO_PIN = 18
LEDS = [Pin(10, Pin.OUT), Pin(11, Pin.OUT), Pin(12, Pin.OUT), Pin(13, Pin.OUT)]
trig = Pin(TRIG_PIN, Pin.OUT)
echo = Pin(ECHO_PIN, Pin.IN)
def medir_distancia():
trig.low()
time.sleep_us(2)
trig.high()
time.sleep_us(10)
trig.low()
duracion = time_pulse_us(echo, 1, 30000) # Máx. 30ms (30000us)
if duracion < 0:
return None
distancia = (duracion * 0.0343) / 2 # Convertir a cm
return distancia
while True:
distancia = medir_distancia()
if distancia is not None:
distancia = max(3, min(25, distancia)) # Limitar valores entre 3 cm y 25 cm
delay = int(30 + (250 - 30) * ((distancia - 3) / (25 - 3))) # Mapear distancia a tiempo
for led in LEDS:
led.on()
time.sleep_ms(delay)
led.off()
else:
print("Error en la medición")
time.sleep(0.1) # Pequeña pausa