import network
import time
from machine import Pin
from umqtt.simple import MQTTClient
# WiFi & MQTT Configuration
WIFI_SSID = "Wokwi-GUEST"
WIFI_PASS = ""
MQTT_BROKER = "broker.hivemq.com"
MQTT_TOPIC = "wokwi-twin"
# Hardware Setup
led = Pin(15, Pin.OUT)
button = Pin(14, Pin.IN, Pin.PULL_UP)
# Connect to WiFi
def connect_wifi():
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
wlan.connect(WIFI_SSID, WIFI_PASS)
while not wlan.isconnected():
print("Connecting to WiFi...")
time.sleep(1)
print("Connected!")
# Handle incoming messages from the Virtual Twin
def sub_cb(topic, msg):
print(f"Twin Command: {msg}")
if msg == b"ON":
led.value(1)
elif msg == b"OFF":
led.value(0)
connect_wifi()
client = MQTTClient("pico_client", MQTT_BROKER)
client.set_callback(sub_cb)
client.connect()
client.subscribe(MQTT_TOPIC)
last_btn_state = 1
while True:
# Check for messages from the Digital Twin
client.check_msg()
# Check for Physical Button Press
btn_state = button.value()
if btn_state != last_btn_state:
if btn_state == 0: # Button Pressed
new_state = "ON" if led.value() == 0 else "OFF"
# Update local LED and notify the Twin
led.value(1 if new_state == "ON" else 0)
client.publish(MQTT_TOPIC, new_state)
print(f"Sent to Twin: {new_state}")
last_btn_state = btn_state
time.sleep(0.1)