🛠 Client MQTT : télémétrie IoT légère sur la Pico W
Objectives
MQTT is THE protocol for IoT devices: lightweight (2-byte header), pub/sub, adapted to unstable radio links. The official MQTT client example is located in pico_w/wifi/ of the pico-examples repository (C SDK); in MicroPython, you can speak MQTT without dependencies by constructing packets manually over a TCP socket — excellent for understanding the protocol. You will implement CONNECT + PUBLISH QoS 0, the pattern for all sensor telemetry.
Hardware
- 1 × Raspberry Pi Pico W + MicroPython
_picowfirmware - An MQTT broker accessible on the LAN (Mosquitto on a NAS/Raspberry Pi 5, or a public test broker — be careful with the data sent)
- Serial console at 115200 bauds; TCP port 1883 open on the broker
Complete code
# mqtt_pub.py — MQTT 3.1.1 minimal (CONNECT + PUBLISH QoS 0) sur socket
import machine, network, socket, time, struct
wlan = network.WLAN; wlan.active(True)
if not wlan.isconnected:
wlan.connect('my_ssid', 'my_password')
while not wlan.isconnected:
machine.idle
def remaining_length(n): # encodage varint MQTT
out = b''
while True:
b = n % 128; n //= 128
if n: b |= 0x80
out += bytes([b])
if not n: return out
def connect(sock, client_id):
proto = b'\x00\x04MQTT\x04\x02\x00\x3c' # level 4, clean session,
cid = struct.pack('>H', len(client_id)) + client_id.encode # keepalive 60s
body = proto + cid
sock.send(b'\x10' + remaining_length(len(body)) + body)
return sock.recv(4) # CONNACK 0x20 0x02 0x00 = accepté
def publish(sock, topic, payload):
t = struct.pack('>H', len(topic)) + topic.encode
p = payload.encode if isinstance(payload, str) else payload
body = t + p
sock.send(b'\x30' + remaining_length(len(body)) + body) # QoS 0
s = socket.socket
s.connect(('192.168.1.10', 1883)) # IP de ton broker
print('CONNACK:', connect(s, 'picow-01'))
while True:
publish(s, 'maison/picow/temperature', '21.5')
time.sleep(10)
# En C SDK : exemple officiel pico_w/wifi/mqtt (lwIP). En MicroPython, la
# lib umqtt.simple existe aussi dans micropython-lib.
# >
# n'a pas été vérifiée (hors base documentaire) — le code ci-dessus s'en passe.
Expected verification
CONNACK: b'\\x20\\x02\\x00' (return code 0 = accepted), then on the broker: mosquitto_sub -t 'maison/picow/#' displays a message every 10 s. Wi-Fi disconnections: the socket breaks — restart the connection in a try/except around the loop for real-world behavior.
Common errors
- Incorrect encoding of the remaining length: the "remaining length" fields are 7-bit varints — a malformed packet causes the broker to eject the client without an error message.
- Staying connected without
ping: the announced keepalive (60 s here) requires the client to send PINGREQ (0xC0), otherwise the broker disconnects it — add a periodic ping for long sessions. client_idconflict: two clients with the same identifier mutually kick each other in a loop — must be unique per board.- QoS 1/2 expected: this example only does QoS 0 (fire and forget); the PUBACK for QoS 1 is not handled.
- Broker on the WAN without TLS: MQTT 1883 in clear text on the Internet = readable credentials; stay on the LAN or add a tunnel.
- In C SDK lwIP threadbackground: forgetting the arch lock around socket calls — see the SDK tutorial.
Other tutorials for this board
- Faire clignoter la LED embarquée (elle est derrière la puce Wi-Fi !)
- Se connecter à un réseau Wi-Fi (station, WPA2/WPA3)
- Bouton et potentiomètre sans marcher sur le sans-fil (GPIO libres & ADC)
- Servir une page web depuis la Pico W (socket TCP + HTTP)
- Client HTTP : consommer une API depuis la Pico W
- Heure exacte via NTP : l'horloge temps réel des projets connectés
Code examples for this board
clignotante.pyPythonbouton-interruption.pyPythonpwm-servo.pyPythonlecture-adc.pyPythonneopixel.pyPythonoled-i2c.pyPython