import machine
import utime
import dht
from machine import Pin, ADC, I2C
# --- CONFIGURACIÓN DE PINES ---
sensor_dht = dht.DHT22(Pin(2))
sensor_luz = ADC(Pin(26))
# Actuador: Servomotor (PWM)
servo = machine.PWM(Pin(15))
servo.freq(50)
# Inicialización de la pantalla LCD (I2C)
i2c = I2C(0, sda=Pin(0), scl=Pin(1), freq=400000)
try:
from pico_i2c_lcd import I2cLcd
lcd = I2cLcd(i2c, 0x27, 2, 16)
except Exception as e:
print("Error al cargar librerías LCD:", e)
lcd = None
def mover_servo(angulo):
duty = int(1800 + (angulo / 180) * 6200)
servo.duty_u16(duty)
def leer_luz_porcentaje():
valor = sensor_luz.read_u16()
return (valor / 65535) * 100
print("Iniciando Sistema Inteligente de Control...")
if lcd:
lcd.putstr("Sistema Listo\nIniciando...")
utime.sleep(2)
while True:
try:
# 1. Captura de datos
sensor_dht.measure()
temp = sensor_dht.temperature()
hum = sensor_dht.humidity()
luz = leer_luz_porcentaje()
# 2. Procesamiento de información en consola
print("-" * 30)
print("Temp: {:.1f}°C | Hum: {:.1f}%".format(temp, hum))
print("Nivel de Luz: {:.1f}%".format(luz))
# 3. Interfaz de Monitoreo (Pantalla LCD)
if lcd:
lcd.clear()
lcd.putstr("T:{:.1f}C H:{:.0f}%\n".format(temp, hum))
if temp > 28.0:
lcd.putstr("VENTILACION: ACT")
else:
lcd.putstr("Ambiente: OK")
# 4. Generación de acciones automáticas (Actuador)
if temp > 28.0:
print("Acción: Temperatura alta. Abriendo ventilación.")
mover_servo(90)
else:
print("Acción: Temperatura normal. Cerrando ventilación.")
mover_servo(0)
utime.sleep(3)
except OSError as e:
print("Error al leer los sensores:", e)
if lcd:
lcd.clear()
lcd.putstr("Error de Lectura\nReintentando...")
utime.sleep(2)