Page 1 of 1

Pi Pico W as MQTT client, asyncio code that works

Posted: Thu Jun 25, 2026 2:00 am
by sam_python
Built sensor node publishing BME280 to Mosquitto. asyncio + umqtt.simple combo works with sharp edges. Sharing for next person.

Code: Select all

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

broker = '192.168.1.10'

async def wifi_connect():
    w = network.WLAN(network.STA_IF)
    w.active(True)
    w.connect('SSID','PASS')
    while not w.isconnected():
        await asyncio.sleep(1)

async def publish_loop():
    i2c = I2C(0, scl=Pin(1), sda=Pin(0))
    bme = bme280.BME280(i2c=i2c)
    c = MQTTClient('pico', broker)
    c.connect()
    while True:
        t,p,h = bme.values
        c.publish(b'sensors/pico', f'{t},{h},{p}'.encode())
        await asyncio.sleep(30)
Gotcha: umqtt.simple blocks on publish. Multi-broker or high-freq, use umqtt.robust + custom non-blocking variant.