Pico 2 W in MicroPython: an MQTT device with telemetry and commands
MicroPython on a Raspberry Pi Pico 2 W joins Wi-Fi, publishes a knob's reading as JSON telemetry every 2 s, and switches an LED from commands the cloud…
Communication · Intermediate
In a real product: Connected greenhouse vent controller (Agriculture): Reports its sensor to the farm's broker and opens or closes its vent when the cloud says so.
An MQTT device keeps one connection open to a broker. It publishes what it measures (telemetry) to one topic and listens on another for what to do (commands). Here a Raspberry Pi Pico 2 W in MicroPython publishes a knob's reading every 2 seconds to farm/vent-3/telemetry and opens or closes its "vent" (an LED on GP15) when the cloud publishes open or close to farm/vent-3/cmd. The simulated broker broker.lab sends those commands at 6 s and 10 s.
What you'll learn
umqtt.simple:MQTTClient,connect(),subscribe(),publish()andcheck_msg()- A retained status and a last will, so a dashboard knows when the device is offline
- Polling for messages with
check_msg()in a loop timed withtime.ticks_ms(), instead of blocking insleep
How it works
After joining TryEmbedded, the program creates an MQTTClient with a client id and the broker's name. Before connecting it sets a last will: offline, retained, on farm/vent-3/status, which the broker publishes for it if the connection drops without a DISCONNECT. Once connected it publishes online to the same topic, retained, so a dashboard that subscribes later sees the current state at once.
subscribe(b"farm/vent-3/cmd") asks the broker for the commands. They arrive only when the program reads the socket: check_msg() reads one if there is one and calls the callback with the topic and the payload as bytes, or returns at once. The loop calls it every 50 ms and publishes the telemetry when 2 s have passed, so commands are handled within 50 ms however long the reporting interval is.
On a real board, umqtt.simple comes from micropython-lib (mip.install("umqtt.simple"), or copy umqtt/simple.py to the board); the simulated Pico 2 W has it already. The broker and its commands are set in diagram.json under "network". Open the Network panel to see the connect, the subscription, every publish and the broker's commands.
Try this
- Add a command
{ "atMs": 8000, "topic": "farm/vent-3/cmd", "payload": "half" }and make the program dim the LED to half withPWM. - Publish the telemetry with
qos=1:publish()then waits for the broker's PUBACK. - Add
"restarts": [12000]to the broker: the connection drops; catch theOSErrorand connect again.
main.py
# Raspberry Pi Pico 2 W (MicroPython): an MQTT device on broker.lab. Telemetry (a knob on GP26) every 2 s as JSON,
# commands "open" / "close" for the vent (an LED on GP15), a retained status and a last will.
import json
import network
import time
from machine import ADC, Pin
from umqtt.simple import MQTTClient
DEVICE = "vent-3"
TELEMETRY = b"farm/vent-3/telemetry"
COMMANDS = b"farm/vent-3/cmd"
STATUS = b"farm/vent-3/status"
knob = ADC(26)
vent = Pin(15, Pin.OUT)
led = Pin("LED", Pin.OUT)
sta = network.WLAN(network.STA_IF)
sta.active(True)
sta.connect("TryEmbedded", "lab-pass-123")
while 0 <= sta.status() < network.STAT_GOT_IP:
time.sleep_ms(100)
print("joined, address", sta.ifconfig()[0])
led.on()
def on_message(topic, payload):
command = payload.decode()
print("command", command)
if command == "open":
vent.on()
elif command == "close":
vent.off()
client = MQTTClient(DEVICE, "broker.lab", keepalive=30)
client.set_callback(on_message)
client.set_last_will(STATUS, b"offline", retain=True)
client.connect()
client.publish(STATUS, b"online", retain=True)
client.subscribe(COMMANDS)
last = time.ticks_add(time.ticks_ms(), -2000)
while True:
client.check_msg()
if time.ticks_diff(time.ticks_ms(), last) >= 2000:
last = time.ticks_ms()
reading = {"device": DEVICE, "humidity": round(knob.read_u16() * 100 / 65535), "vent": vent.value()}
client.publish(TELEMETRY, json.dumps(reading))
print("telemetry", reading)
time.sleep_ms(50)