Pi Pico W as MQTT client, full asyncio code that works

MicroPython on ESP32, Pi Pico, and other supported boards.
Post Reply
sam_python
Posts: 6
Joined: Tue May 05, 2026 11:00 am

Building a sensor node that publishes BME280 readings to a Mosquitto broker. asyncio + umqtt.simple combo works but had some sharp edges. Sharing for the next person.

Code: Select all

import uasyncio as asyncio
from machine import Pin, I2C
from umqtt.simple import MQTTClient
import network, bme280

ssid = 'YourWiFi'
password = 'YourPass'
broker = '192.168.1.10'

async def wifi_connect():
    w = network.WLAN(network.STA_IF)
    w.active(True)
    w.connect(ssid, password)
    while not w.isconnected():
        await asyncio.sleep(1)
    print('wifi:', w.ifconfig())

async def publish_loop():
    i2c = I2C(0, scl=Pin(1), sda=Pin(0))
    bme = bme280.BME280(i2c=i2c)
    client = MQTTClient('pico', broker)
    client.connect()
    while True:
        t, p, h = bme.values
        client.publish(b'sensors/pico', f'{t},{h},{p}'.encode())
        await asyncio.sleep(30)

async def main():
    await wifi_connect()
    await publish_loop()

asyncio.run(main())
Gotcha: umqtt.simple blocks during publish. For high-frequency publishes or multi-broker setups use umqtt.robust + custom non-blocking variant. Production code mas malalim.
Post Reply