from machine import Pin, I2C, PWM
from hcsr04 import HCSR04
from time import sleep
from lcd_api import LcdApi
from i2c_lcd import I2cLcd
# CONFIGURACIÓN DEL SENSOR
sensor = HCSR04(trigger_pin=5, echo_pin=18, echo_timeout_us=10000)
# LEDS
led_verde = Pin(27, Pin.OUT)
led_amarillo = Pin(26, Pin.OUT)
led_rojo = Pin(25, Pin.OUT)
# BUZZER
buzzer = PWM(Pin(23))
buzzer.duty(0) # apagado
# LCD I2C
I2C_ADDR = 0x27
I2C_BUS = I2C(0, scl=Pin(22), sda=Pin(21), freq=100000)
lcd = I2cLcd(I2C_BUS, I2C_ADDR, 2, 16)
# FUNCIÓN BUZZER
def sonar_buzzer(duracion_ms=100):
buzzer.freq(2000) # frecuencia
buzzer.duty(512)
sleep(duracion_ms / 1000)
buzzer.duty(0) # apaga el buzzer
# BUCLE PRINCIPAL
while True:
try:
distancia = sensor.distance_cm() # medir distancia
lcd.clear()
lcd.putstr("Distancia: {:.1f}cm".format(distancia))
print("Distancia: {:.1f} cm".format(distancia))
if 80 <= distancia <= 120:
led_verde.on()
led_amarillo.off()
led_rojo.off()
sonar_buzzer(100)
sleep(2)
elif 40 <= distancia < 80:
led_verde.off()
led_amarillo.on()
led_rojo.off()
sonar_buzzer(100)
sleep(1)
elif 4 <= distancia < 40:
led_verde.off()
led_amarillo.off()
led_rojo.on()
sonar_buzzer(100)
sleep(0.5)
else:
led_verde.off()
led_amarillo.off()
led_rojo.off()
buzzer.duty(0)
sleep(0.2)
except OSError as e:
print("Error al leer el sensor:", e)
lcd.clear()
lcd.putstr("Error sensor")
sleep(1)