import time
import machine
import network
from machine import Pin, ADC
from umqtt.simple import MQTTClient
# Configuración WiFi y MQTT
ssid = 'Wokwi-GUEST'
wifipassword = ''
mqtt_server = 'io.adafruit.com'
port = 1883
user = 'gonzaborgono'
password = 'aio_zPLF60qytqQGQnuUwdSOReklrReV'
client_id = 'LamparaNoche'
# Conexión con tópicos de Adafruit
topic_ActivarSensor = 'gonzaborgono/feeds/ActivarSensor' #activar/desactivar LDR (ON/OFF)
topic_UmbralLuz = 'gonzaborgono/feeds/UmbralLuz' #oscuridad necesaria para encender luz (0-4095)
topic_SensorLuz = 'gonzaborgono/feeds/SensorLuz' #valor que lee el LDR (resistencia a luz/oscuridad, 0-4095)
topic_Relay = 'gonzaborgono/feeds/Relay' #estado del relay (led/lampara apagada o encendida)
# Inicializamos variables
SENSOR_ACTIVO = False
UMBRAL_LUZ = 3500 # Valor por defecto para resistencia en oscuridad
ULT_ESTADO_RELAY = None
ULT_LECTURA_LDR = None
ULT_UMBRAL = None
ULT_ESTADO_SENSOR = None
# Conexión WiFi
sta_if = network.WLAN(network.STA_IF)
sta_if.active(True)
sta_if.connect(ssid, wifipassword)
print("Conectando a WiFi", end="")
while not sta_if.isconnected():
print(".", end="")
time.sleep(0.1)
print("\nConectado a WiFi")
# Hardware
ldr = ADC(Pin(34))
ldr.atten(ADC.ATTN_11DB) # Rango de 0-4095 (0 = max. luz | 4095 = max. oscuridad)
relay = Pin(15, Pin.OUT)
relay.value(0)
# Callback MQTT
def callback_mqtt(topic, msg):
global SENSOR_ACTIVO, UMBRAL_LUZ
topic_str = topic.decode('utf-8')
dato = msg.decode('utf-8')
print(f"Mensaje recibido -> {topic_str}: {dato}")
if topic_str == topic_ActivarSensor:
SENSOR_ACTIVO = (dato.upper() == "ON") #si el sensor esta en ON la condicion devuelve True, sino False
elif topic_str == topic_UmbralLuz:
UMBRAL_LUZ = int(dato)
# Iniciar MQTT y sincronizar con Adafruit IO
client = MQTTClient(client_id, mqtt_server, user=user, password=password, port=port)
client.set_callback(callback_mqtt)
client.connect()
client.subscribe(topic_ActivarSensor)
client.subscribe(topic_UmbralLuz)
# Inicializar valores en el dashboard
client.publish(topic_ActivarSensor, "ON" if SENSOR_ACTIVO else "OFF", retain=True)
client.publish(topic_UmbralLuz, str(UMBRAL_LUZ), retain=True)
print("Conectado a Adafruit IO")
# Bucle principal
while True:
try:
client.check_msg()
resistencia_ldr = ldr.read()
print(f"Resistencia LDR/Oscuridad: {resistencia_ldr}, Umbral: {UMBRAL_LUZ}")
if ((ULT_LECTURA_LDR != resistencia_ldr or ULT_UMBRAL != UMBRAL_LUZ) or ULT_ESTADO_SENSOR != SENSOR_ACTIVO):
# Publicar siempre el valor de resistencia
client.publish(topic_SensorLuz, str(resistencia_ldr))
if SENSOR_ACTIVO:
# Control del relay basado en resistencia
if resistencia_ldr >= UMBRAL_LUZ and ULT_ESTADO_RELAY != "ON":
relay.value(1)
client.publish(topic_Relay, "ON", retain=True)
ULT_ESTADO_RELAY = "ON"
elif resistencia_ldr < UMBRAL_LUZ and ULT_ESTADO_RELAY != "OFF":
relay.value(0)
client.publish(topic_Relay, "OFF", retain=True)
ULT_ESTADO_RELAY = "OFF"
else:
if ULT_ESTADO_SENSOR != "OFF":
relay.value(0)
client.publish(topic_Relay, "OFF", retain=True)
ULT_ESTADO_RELAY = "OFF"
ULT_LECTURA_LDR = resistencia_ldr
ULT_UMBRAL = UMBRAL_LUZ
ULT_ESTADO_SENSOR = SENSOR_ACTIVO
time.sleep(3)
except Exception as e:
print("Error:", e)
time.sleep(10)
machine.reset()