import network
import time
from machine import Pin, ADC
from umqtt.simple import MQTTClient
# Configuración MQTT
MQTT_CLIENT_ID = "micropython-led-control"
MQTT_BROKER = "broker.mqttdashboard.com"
MQTT_TOPIC = "led/control" # Tópico al que se suscribirá
MQTT_STATUS = "led/status" # Tópico para publicar el estado del LED
# Inicializar LED en pin 2
led = Pin(2, Pin.OUT)
# Inicializar sensor de luz en pin ADC (GPIO34)
ldr = ADC(Pin(34))
ldr.atten(ADC.ATTN_11DB) # Configurar rango de lectura (0-3.3V)
# Umbral de luz (ajusta según sea necesario)
LIGHT_THRESHOLD = 2000 # Valor bajo indica oscuridad
# Estado del LED
led_state = 0 # 0 = Apagado, 1 = Encendido
# Función callback que se ejecuta al recibir un mensaje
def on_message(topic, msg):
global led_state
print("Mensaje recibido:", msg)
if msg == b"ON":
led.value(1)
led_state = 1
print("LED ENCENDIDO")
elif msg == b"OFF":
led.value(0)
led_state = 0
print("LED APAGADO")
# Publicar el estado del LED en MQTT
def publish_led_status():
client.publish(MQTT_STATUS, str(led_state))
# Conexión WiFi
print("Conectando al WiFi...", end="")
sta_if = network.WLAN(network.STA_IF)
sta_if.active(True)
sta_if.connect('Wokwi-GUEST', '')
while not sta_if.isconnected():
print(".", end="")
time.sleep(0.1)
print(" ¡Conectado!")
# Conexión al broker MQTT
print("Conectando al broker MQTT... ", end="")
client = MQTTClient(MQTT_CLIENT_ID, MQTT_BROKER)
client.set_callback(on_message)
client.connect()
client.subscribe(MQTT_TOPIC)
print("¡Conectado y suscrito al tópico!")
# Bucle principal
try:
while True:
# Leer el valor del sensor de luz
light_value = ldr.read()
print("Valor del sensor de luz:", light_value)
# Control automático del LED
if light_value < LIGHT_THRESHOLD and led_state == 0:
led.value(1)
led_state = 1
print("AUTO: LED ENCENDIDO")
publish_led_status()
elif light_value >= LIGHT_THRESHOLD and led_state == 1:
led.value(0)
led_state = 0
print("AUTO: LED APAGADO")
publish_led_status()
# Revisar si hay mensajes nuevos en MQTT
client.check_msg()
time.sleep(0.5)
except KeyboardInterrupt:
print("Desconectando...")
client.disconnect()