import network
import time
from machine import Pin
from umqtt.simple import MQTTClient
# Wi-Fi 配置
WIFI_SSID = "Wokwi-GUEST"
WIFI_PASSWORD = ""
# MQTT 配置
MQTT_CLIENT_ID = "esp32-led-demo"
MQTT_BROKER = "broker.mqttdashboard.com"
MQTT_USER = ""
MQTT_PASSWORD = ""
MQTT_TOPIC = "esp32led"
# 配置 LED 引脚(15 号引脚)
led = Pin(15, Pin.OUT)
led.off() # 初始状态:关闭
# MQTT 回调函数,处理接收到的消息
def on_message(topic, msg):
print(f"Received message on topic {topic.decode()}: {msg.decode()}")
if msg.decode().lower() == "on":
led.on()
print("LED turned ON")
elif msg.decode().lower() == "off":
led.off()
print("LED turned OFF")
# 连接到 Wi-Fi
print("Connecting to WiFi", end="")
sta_if = network.WLAN(network.STA_IF)
sta_if.active(True)
sta_if.connect(WIFI_SSID, WIFI_PASSWORD)
while not sta_if.isconnected():
print(".", end="")
time.sleep(0.1)
print(" Connected!")
# 连接到 MQTT 经纪人
print("Connecting to MQTT server...", end="")
client = MQTTClient(MQTT_CLIENT_ID, MQTT_BROKER, user=MQTT_USER, password=MQTT_PASSWORD)
client.set_callback(on_message)
client.connect()
client.subscribe(MQTT_TOPIC)
print("Connected and subscribed to topic:", MQTT_TOPIC)
# 主循环:检查 MQTT 消息
while True:
client.check_msg()
time.sleep(0.1)