from machine import Pin
import time
import onewire
import ds18x20
import dht
import random
import sys
# Configuración LED RGB (cátodo común)
red = Pin(13, Pin.OUT)
green = Pin(14, Pin.OUT)
blue = Pin(15, Pin.OUT)
# Rangos de alerta
TEMP_GREEN = (18, 26)
TEMP_YELLOW = [(15, 17), (27, 30)]
HUM_GREEN = (40, 60)
HUM_YELLOW = [(30, 39), (61, 70)]
PRES_GREEN = (1010, 1025)
PRES_YELLOW = [(1000, 1009), (1026, 1035)]
# Configuración sensores
ds_pin = Pin(22) # DS18B20 en GP22
ds_sensor = ds18x20.DS18X20(onewire.OneWire(ds_pin))
dht_sensor = dht.DHT22(Pin(16)) # DHT22 en GP16
def set_led_color(r, g, b):
"""Controla el LED RGB"""
print(f"LED: R={r}, G={g}, B={b}")
red.value(r)
green.value(g)
blue.value(b)
def test_leds():
"""Prueba exhaustiva de LEDs"""
print("\n" + "="*50)
print("PRUEBA DE LEDS RGB")
print("="*50)
# Prueba individual de colores
for color, pin in [("ROJO", red), ("VERDE", green), ("AZUL", blue)]:
print(f"Encendiendo {color}")
pin.on()
time.sleep(1)
pin.off()
time.sleep(0.3)
# Prueba de combinaciones
combinations = [
("ROJO", [1, 0, 0]),
("VERDE", [0, 1, 0]),
("AZUL", [0, 0, 1]),
("AMARILLO", [1, 1, 0]),
("BLANCO", [1, 1, 1]),
("APAGADO", [0, 0, 0])
]
for name, values in combinations:
print(f"Mostrando {name}")
set_led_color(*values)
time.sleep(1.5)
print("Prueba de LEDs completada!\n")
def init_sensors():
"""Inicialización de sensores con diagnóstico"""
global roms
print("\n" + "="*50)
print("INICIALIZACIÓN DE SENSORES")
print("="*50)
# Detección de DS18B20
roms = []
try:
print("Buscando sensores DS18B20...")
roms = ds_sensor.scan()
if roms:
print(f" Encontrados {len(roms)} sensores")
# Primera lectura para calentar
ds_sensor.convert_temp()
time.sleep(1)
else:
print(" No se detectaron sensores DS18B20")
except Exception as e:
print(f" Error en DS18B20: {e}")
# Prueba de DHT22
try:
print("Probando DHT22...")
dht_sensor.measure()
hum = dht_sensor.humidity()
print(f" Humedad inicial: {hum:.1f}%")
except Exception as e:
print(f" Error en DHT22: {e}")
print("Inicialización de sensores completada!")
def read_sensors():
"""Lectura de sensores con valores simulados si es necesario"""
temp = hum = None
# Leer temperatura DS18B20
if roms:
try:
ds_sensor.convert_temp()
time.sleep(0.75)
temp = ds_sensor.read_temp(roms[0])
except Exception as e:
print(f"Error leyendo DS18B20: {e}")
# Leer humedad DHT22
try:
dht_sensor.measure()
hum = dht_sensor.humidity()
except Exception as e:
print(f"Error leyendo DHT22: {e}")
# Valores por defecto si hay error
temp = temp if temp is not None else random.uniform(10, 35)
hum = hum if hum is not None else random.uniform(20, 80)
pres = 1015 + random.uniform(-10, 10) # Presión simulada
print(f"\nLectura de sensores:")
print(f" Temperatura: {temp:.1f}°C")
print(f" Humedad: {hum:.1f}%")
print(f" Presión: {pres:.1f} hPa")
return temp, hum, pres
def evaluate_conditions(temp, hum, pres):
"""Evalúa las condiciones y determina el estado"""
# Evaluar temperatura
if TEMP_GREEN[0] <= temp <= TEMP_GREEN[1]:
temp_status = 0
elif any(low <= temp <= high for low, high in TEMP_YELLOW):
temp_status = 1
else:
temp_status = 2
# Evaluar humedad
if HUM_GREEN[0] <= hum <= HUM_GREEN[1]:
hum_status = 0
elif any(low <= hum <= high for low, high in HUM_YELLOW):
hum_status = 1
else:
hum_status = 2
# Evaluar presión
if PRES_GREEN[0] <= pres <= PRES_GREEN[1]:
pres_status = 0
elif any(low <= pres <= high for low, high in PRES_YELLOW):
pres_status = 1
else:
pres_status = 2
# Determinar estado general
if any(status == 2 for status in [temp_status, hum_status, pres_status]):
return 2 # Rojo
elif any(status == 1 for status in [temp_status, hum_status, pres_status]):
return 1 # Amarillo
return 0 # Verde
def simulate_conditions():
"""Simula diferentes condiciones para probar el sistema"""
test_cases = [
# (temp, hum, pres, estado_esperado)
(22, 50, 1015, 0), # Óptimo
(28, 65, 1030, 1), # Advertencia
(14, 75, 990, 2), # Alerta
(26, 40, 1015, 0), # Óptimo
(30, 60, 1015, 1), # Advertencia (temp alta)
(17, 35, 1015, 1), # Advertencia (temp baja)
(25, 75, 1015, 2) # Alerta (humedad alta)
]
print("\n" + "="*50)
print("PRUEBA DE SIMULACIÓN DE CONDICIONES")
print("="*50)
for i, (temp, hum, pres, expected) in enumerate(test_cases):
print(f"\nPrueba #{i+1}: Temp={temp}°C, Hum={hum}%, Pres={pres}hPa")
status = evaluate_conditions(temp, hum, pres)
# Controlar LED
if status == 0: # Verde
set_led_color(0, 1, 0)
elif status == 1: # Amarillo
set_led_color(1, 1, 0)
elif status == 2: # Rojo
set_led_color(1, 0, 0)
print(f"Estado detectado: {['VERDE','AMARILLO','ROJO'][status]}")
print(f"Estado esperado: {['VERDE','AMARILLO','ROJO'][expected]}")
print("Resultado: " + ("ÉXITO" if status == expected else "FALLO"))
time.sleep(3)
# Apagar LED al final
set_led_color(0, 0, 0)
def main():
"""Función principal para pruebas"""
print("\n" + "="*50)
print("SISTEMA DE MONITOREO - MODO PRUEBA")
print("="*50)
# 1. Prueba inicial de LEDs
test_leds()
# 2. Inicialización de sensores
init_sensors()
# 3. Prueba de simulación
simulate_conditions()
# 4. Prueba en tiempo real con sensores
print("\n" + "="*50)
print("PRUEBA EN TIEMPO REAL CON SENSORES")
print("="*50)
print("Presione Ctrl+C para detener...")
try:
while True:
# Leer sensores
temp, hum, pres = read_sensors()
# Determinar estado
status = evaluate_conditions(temp, hum, pres)
# Controlar LED
if status == 0: # Verde
set_led_color(0, 1, 0)
elif status == 1: # Amarillo
set_led_color(1, 1, 0)
elif status == 2: # Rojo
set_led_color(1, 0, 0)
print(f"Estado actual: {['VERDE','AMARILLO','ROJO'][status]}")
time.sleep(5)
except KeyboardInterrupt:
print("\nPrueba detenida por el usuario")
set_led_color(0, 0, 0)
if __name__ == "__main__":
try:
main()
except Exception as e:
print("\nERROR CRÍTICO:", e)
# Secuencia de error: LED blanco intermitente
while True:
set_led_color(1, 1, 1)
time.sleep(0.5)
set_led_color(0, 0, 0)
time.sleep(0.5)Loading
pi-pico-w
pi-pico-w