from machine import Pin
import dht
import time
import math
# ==============================
# Variables de control
# ==============================
SET_TEMP = 50
# ==============================
# Configuración del DHT22
# ==============================
DHT_PIN = 15
sensor = dht.DHT22(Pin(DHT_PIN))
# ==============================
# Configuración de LEDs
# ==============================
LED_VERDE_PIN = 18
LED_ROJO_PIN = 19
led_verde = Pin(LED_VERDE_PIN, Pin.OUT)
led_rojo = Pin(LED_ROJO_PIN, Pin.OUT)
# Estado inicial
led_verde.off()
led_rojo.off()
# ==============================
# Configuración general
# ==============================
INTERVALO_LECTURA = 2000
ultimo_tiempo = time.ticks_ms()
print("-------------------------------------")
print("Monitor de temperatura y humedad")
print("-------------------------------------")
while True:
tiempo_actual = time.ticks_ms()
if time.ticks_diff(tiempo_actual, ultimo_tiempo) >= INTERVALO_LECTURA:
ultimo_tiempo = tiempo_actual
temperatura = None
humedad = None
# Intentar leer hasta 3 veces
for intento in range(3):
try:
sensor.measure()
temperatura = sensor.temperature()
humedad = sensor.humidity()
break
except OSError:
print("Intento de lectura fallido:", intento + 1)
time.sleep_ms(200)
# Verificar si se logró obtener una lectura
if temperatura is None or humedad is None:
print("Error: No fue posible leer el sensor DHT22.")
led_verde.off()
led_rojo.off()
continue
# Verificar que los datos sean numéricos
if math.isnan(temperatura) or math.isnan(humedad):
print("Error: Lectura inválida.")
led_verde.off()
led_rojo.off()
continue
# Verificar rango válido del DHT22
if humedad < 0 or humedad > 100 or temperatura < -40 or temperatura > 80:
print("Error: Lectura fuera de rango.")
led_verde.off()
led_rojo.off()
continue
# ==============================
# Control de LEDs
# ==============================
if temperatura >= SET_TEMP:
led_rojo.on()
led_verde.off()
estado = "ALARMA - LED ROJO"
else:
led_rojo.off()
led_verde.on()
estado = "NORMAL - LED VERDE"
# ==============================
# Mostrar resultados
# ==============================
print("-------------------------------------")
print("Humedad: {:.1f} %".format(humedad))
print("Temperatura: {:.1f} °C".format(temperatura))
print("Estado:", estado)
print("-------------------------------------")