import machine
import time
import network
from umqtt.simple import MQTTClient
# Define the pin connected to the LED
led_pin = machine.Pin(12, machine.Pin.OUT)
# MQTT Server Configuration (Replace with your details if needed)
MQTT_CLIENT_ID = "micropython-input-demo"
MQTT_BROKER = "broker.mqttdashboard.com"
MQTT_USER = "" # Update with username if required
MQTT_PASSWORD = "" # Update with password if required
MQTT_TOPIC = "led_test"
# Connect to WiFi Network (Replace with your network details if needed)
print("Connecting to WiFi", end="")
sta_if = network.WLAN(network.STA_IF)
sta_if.active(True)
sta_if.connect('Wokwi-GUEST', '') # Update with your WiFi SSID and password
while not sta_if.isconnected():
print(".", end="")
time.sleep(0.1)
print(" Connected!")
# Connect to MQTT Broker
print("Connecting to MQTT server... ", end="")
client = MQTTClient(MQTT_CLIENT_ID, MQTT_BROKER, user=MQTT_USER, password=MQTT_PASSWORD)
client.connect()
print("Connected!")
def on_message(topic, msg):
# This function will be called whenever a message is received on the subscribed topic
print("Received message:", msg) # Print the received message
if msg == b"on":
led_pin.value(1) # Turn LED on
print("LED turned ON")
# You can publish a message back indicating LED state (optional)
client.publish(MQTT_TOPIC, "LED_ON")
elif msg == b"off":
led_pin.value(0) # Turn LED off
print("LED turned OFF")
# You can publish a message back indicating LED state (optional)
client.publish(MQTT_TOPIC, "LED_OFF")
# Set the message callback function
client.set_callback(on_message)
# Subscribe to the MQTT topic for receiving LED control commands
client.subscribe(MQTT_TOPIC)
# Main loop to keep the connection alive and check for messages
while True:
client.check_msg() # Check for incoming messages
time.sleep(0.1) # Sleep for a short interval