MQTT_Aug7CreativeTech/rp2040_client/main.py

60 lines
1.4 KiB
Python
Raw Normal View History

2024-08-06 15:33:18 +00:00
import time
2024-08-08 00:18:07 +00:00
from machine import Pin
2024-08-06 15:33:18 +00:00
from umqtt.simple import MQTTClient
import network
import time
from math import sin
2024-08-08 00:18:07 +00:00
led = Pin("LED", Pin.OUT)
led.value(1)
button = Pin(14, Pin.IN, Pin.PULL_UP)
2024-08-06 15:33:18 +00:00
# Received messages from subscriptions will be delivered to this callback
def sub_cb(topic, msg):
print((topic, msg))
2024-08-08 00:18:07 +00:00
if msg == b'on':
print("turn LED on")
led.value(1)
elif msg == b'off':
print("turn LED off")
led.value(0)
2024-08-06 15:33:18 +00:00
def main(server="192.168.1.59"):
# Fill in your WiFi network name (ssid) and password here:
wifi_ssid = "OddlyAsus"
wifi_password = "8699869986"
# Connect to WiFi
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
wlan.connect(wifi_ssid, wifi_password)
while wlan.isconnected() == False:
print('Waiting for connection...')
time.sleep(1)
print("Connected to WiFi")
c = MQTTClient("pico_board", server, 1883)
c.set_callback(sub_cb)
c.connect()
c.subscribe(b"godot/#")
while True:
if True:
# Blocking wait for message
c.wait_msg()
else:
# Non-blocking wait for message
c.check_msg()
# Then need to sleep to avoid 100% CPU usage (in a real
# app other useful actions would be performed instead)
time.sleep(1)
c.disconnect()
if __name__ == "__main__":
main()