From a37409e5e7a51a86637aee05bbd70b3a31b2024b Mon Sep 17 00:00:00 2001 From: Edward Bigos Date: Tue, 7 Apr 2026 11:02:20 -0400 Subject: [PATCH] Added Lab 10 file --- Lab10/MicroPython/Code/ReadFeedLED2.py | 95 ++++++++++++++++++++++++++ 1 file changed, 95 insertions(+) create mode 100644 Lab10/MicroPython/Code/ReadFeedLED2.py diff --git a/Lab10/MicroPython/Code/ReadFeedLED2.py b/Lab10/MicroPython/Code/ReadFeedLED2.py new file mode 100644 index 0000000..c4c93b7 --- /dev/null +++ b/Lab10/MicroPython/Code/ReadFeedLED2.py @@ -0,0 +1,95 @@ +import network +import time +from umqtt.simple import MQTTClient +import secrets + +# Global variable +tsetting = False +last_tsetting = None # Track changes + +# WiFi setup +def connect_wifi(): + wlan = network.WLAN(network.STA_IF) + wlan.active(True) + wlan.connect(secrets.WIFI_SSID, secrets.WIFI_PASSWORD) + + print("Connecting to WiFi...") + while not wlan.isconnected(): + time.sleep(1) + + print("Connected:", wlan.ifconfig()) + +# MQTT callback +def message_callback(topic, msg): + topic = topic.decode() + msg = msg.decode() + + print("Received:", topic, msg) + + if topic.endswith("/mytemperaturesetting"): + try: + value = int(msg) + print("temperaturesetting value:", value) + except: + print("Invalid temperaturesetting value") + + elif topic.endswith("/led"): + print("LED command:", msg) + +# MQTT setup +def connect_mqtt(): + client_id = "picoW-client" + broker = "io.adafruit.com" + port = 1883 + + username = secrets.AIO_USERNAME + password = secrets.AIO_KEY + + client = MQTTClient(client_id, broker, port=port, + user=username, password=password) + + client.set_callback(message_callback) + client.connect() + + # Feed paths + temperaturesetting_feed = f"{username}/feeds/mytemperaturesetting" + led_feed = f"{username}/feeds/led" + + # Subscribe + client.subscribe(temperaturesetting_feed) + client.subscribe(led_feed) + + print("Subscribed to feeds") + return client, led_feed + +# Publish function +def publish_led(client, led_feed, value): + msg = "ON" if value else "OFF" + client.publish(led_feed, msg) + print("Published to LED feed:", msg) + +# Main loop +def main(): + global tsetting, last_tsetting + + connect_wifi() + client, led_feed = connect_mqtt() + + print("Running...") + + while True: + client.check_msg() + + # 🔁 Example: toggle tsetting every 10 seconds (replace with real logic) +# if int(time.time()) % 10 == 0: +# tsetting = not tsetting + + # ✅ Only publish if value changed + if tsetting != last_tsetting: + publish_led(client, led_feed, tsetting) + last_tsetting = tsetting + + time.sleep(2) + +# Run +main() \ No newline at end of file