Sub topic 9
Messaging with MQTT
MQTT is a lightweight publish/subscribe protocol that suits small devices on unreliable networks. This chapter assumes you can already join a Wi-Fi network with WiFi.begin(), keep credentials in arduino_secrets.h, and use WiFiClient for a TCP connection. The examples use a WiFiNINA board such as the MKR WiFi 1010 or Nano 33 IoT, together with the ArduinoMqttClient library from the Library Manager.
Why MQTT instead of HTTP
An HTTP request is a conversation you start. Your board asks, the server answers, and the connection closes. That works for fetching a page, but it is a poor fit for a device that must react the moment something happens elsewhere. You would have to poll, which wastes power and bandwidth and still adds delay.
MQTT keeps one long-lived TCP connection open between the board and a server called a broker. Messages flow in both directions over that connection. Each message has a topic, a text label such as home/livingroom/temperature, and a payload, the bytes you send. Clients do not talk to each other directly. A client publishes a message to a topic, and the broker forwards it to every client that has subscribed to that topic.
This has two consequences. The publisher and subscriber need not know about each other or be online at the same time. And the board needs only one outbound connection to the broker, so it works behind a home router without any port forwarding.
Topics and wildcards
Topics are case-sensitive strings split into levels by /. You choose the names, but a consistent scheme saves trouble later. A common pattern is site/device/measurement, for example lab/board1/temperature.
Subscribers can use two wildcards. Publishers cannot, because a publish always targets one exact topic.
| Wildcard | Meaning | Example filter | Matches |
|---|---|---|---|
| `+` | Exactly one level | `lab/+/temperature` | `lab/board1/temperature`, `lab/board2/temperature` |
| `#` | All remaining levels, must be last | `lab/#` | `lab/board1/temperature`, `lab/board1/led/state` |
Avoid a leading /, which creates an empty first level. Topics starting with $ are reserved by many brokers for their own statistics.
Choosing a broker
You can run a broker such as Mosquitto on a Raspberry Pi or a PC on your network, or use a hosted broker. Public test brokers are fine for a first experiment, but anyone can read and write your topics there, so never send anything private. For real use, run your own or use a hosted broker that requires a username and password.
The sketches below use broker.example.com as a placeholder. Replace it with your broker's hostname or IP address.
Publishing
This sketch connects and publishes the uptime in seconds every five seconds. The important detail is poll().
#include <WiFiNINA.h>
#include <ArduinoMqttClient.h>
#include "arduino_secrets.h"
WiFiClient wifiClient;
MqttClient mqttClient(wifiClient);
const char broker[] = "broker.example.com";
const int port = 1883;
const char topic[] = "demo/uptime";
unsigned long lastSend = 0;
void setup() {
Serial.begin(115200);
while (!Serial && millis() < 5000) {}
while (WiFi.begin(SECRET_SSID, SECRET_PASS) != WL_CONNECTED) {
delay(5000);
}
if (!mqttClient.connect(broker, port)) {
Serial.print("MQTT connection failed, error ");
Serial.println(mqttClient.connectError());
while (true) {}
}
}
void loop() {
mqttClient.poll();
if (millis() - lastSend >= 5000) {
lastSend = millis();
mqttClient.beginMessage(topic);
mqttClient.print(millis() / 1000);
mqttClient.endMessage();
}
}beginMessage() starts a message, and everything you print() becomes the payload. endMessage() sends it. Because the message is built through the Print interface, print, println, and write all work as they do for Serial.
Why poll() matters
MQTT has a keep-alive interval. If the broker hears nothing from the client for about one and a half times that interval, it assumes the client is dead and closes the connection. poll() sends the small ping packets that keep the session alive and also reads any incoming messages. If your loop() blocks in a long delay() or a slow sensor read, poll() is not called and the broker will drop you. Call it on every pass, and replace long delays with millis() timing.
Subscribing
To receive messages, register a callback with onMessage() and call subscribe() after connecting. The library calls your callback from inside poll(), so the callback runs in your normal program flow and not in an interrupt.
The next sketch switches the built-in LED on or off when the payload of demo/led/set is on or off. It also reconnects without blocking, using the same millis() pattern as the previous chapter.
#include <WiFiNINA.h>
#include <ArduinoMqttClient.h>
#include "arduino_secrets.h"
WiFiClient wifiClient;
MqttClient mqttClient(wifiClient);
const char broker[] = "broker.example.com";
const int port = 1883;
const char commandTopic[] = "demo/led/set";
const unsigned long RETRY_INTERVAL_MS = 10000;
unsigned long lastAttempt = 0;
void onMqttMessage(int messageSize) {
String payload;
payload.reserve(messageSize);
while (mqttClient.available()) {
payload += (char)mqttClient.read();
}
Serial.print(mqttClient.messageTopic());
Serial.print(": ");
Serial.println(payload);
if (payload == "on") {
digitalWrite(LED_BUILTIN, HIGH);
} else if (payload == "off") {
digitalWrite(LED_BUILTIN, LOW);
}
}
void ensureConnected() {
if (WiFi.status() == WL_CONNECTED && mqttClient.connected()) return;
if (millis() - lastAttempt < RETRY_INTERVAL_MS) return;
lastAttempt = millis();
if (WiFi.status() != WL_CONNECTED) {
Serial.println("Wi-Fi down, reconnecting");
WiFi.begin(SECRET_SSID, SECRET_PASS);
return;
}
Serial.println("Connecting to broker");
if (mqttClient.connect(broker, port)) {
mqttClient.subscribe(commandTopic);
Serial.println("Subscribed");
} else {
Serial.print("MQTT error ");
Serial.println(mqttClient.connectError());
}
}
void setup() {
Serial.begin(115200);
pinMode(LED_BUILTIN, OUTPUT);
mqttClient.onMessage(onMqttMessage);
WiFi.begin(SECRET_SSID, SECRET_PASS);
}
void loop() {
ensureConnected();
if (mqttClient.connected()) {
mqttClient.poll();
}
}To test it, publish from a PC with the Mosquitto client tools: mosquitto_pub -h broker.example.com -t demo/led/set -m on.
Two details are easy to miss:
- Subscriptions do not survive a reconnect. The sketch calls
subscribe()inside the successful-connect branch, so it is repeated every time. If you subscribe only insetup(), the board will connect again after a drop and never receive anything. - Read the whole message. Drain the payload with
available()andread()inside the callback. Leftover bytes from one message can corrupt the next.
Keep callbacks short. Set a flag or copy the value, and do slow work later in loop(), because a slow callback delays poll() just as a delay() would.
Quality of service, retain, and last will
The publish call accepts more options than the basic form. The third argument is the quality of service (QoS).
| QoS | Guarantee | Cost |
|---|---|---|
| 0 | At most once. Fire and forget, so the message can be lost. | Lowest |
| 1 | At least once. The message is acknowledged and may arrive twice. | One extra packet |
| 2 | Exactly once. | Four-packet handshake |
For sensor readings sent every few seconds, QoS 0 is usually enough, because the next reading replaces a lost one. For commands that must not be missed, use QoS 1 and make the receiver tolerate duplicates. For example, "set LED on" is safe to repeat, but "toggle LED" is not. QoS applies separately to each hop, from publisher to broker and from broker to subscriber, and the lower of the two settings wins.
A retained message is stored by the broker and delivered immediately to any new subscriber of that topic. This suits state, such as the last known LED setting, so a dashboard that starts late still sees a value:
// beginMessage(topic, retain, qos)
mqttClient.beginMessage("demo/led/state", true, 1);
mqttClient.print("on");
mqttClient.endMessage();A last will is a message you register with the broker before connecting. The broker publishes it for you if the board disappears without a clean disconnect. Combined with a retained "online" message, it lets other clients see whether the board is alive. Use mqttClient.beginWill(topic, retain, qos), print the payload, then call endWill(). Do this before connect().
Client IDs, authentication, and TLS
Every client has an ID. Two clients that connect with the same ID make the broker disconnect the older one, so two identical boards can fight and keep kicking each other off. Set a unique ID before connecting with mqttClient.setId("board-1");. Without it the library generates a random one.
Most real brokers require credentials. Call mqttClient.setUsernamePassword(SECRET_MQTT_USER, SECRET_MQTT_PASS); before connect(), and define those two values in arduino_secrets.h alongside the Wi-Fi settings so they stay out of version control.
Port 1883 is plain text, so the username, password, and payloads cross the network unencrypted. For anything beyond a test, use TLS on port 8883. Construct the MQTT client over a WiFiSSLClient instead of a WiFiClient:
WiFiSSLClient wifiClient;
MqttClient mqttClient(wifiClient);
// then: mqttClient.connect("broker.example.com", 8883)As with HTTPS, the broker's root certificate must be in the Wi-Fi module's certificate store, or the connection fails.
Common failures
| Symptom | Likely cause |
|---|---|
| `connectError()` returns -2 | The TCP connection failed. Check the broker address, port, and firewall. |
| Connection works, then drops after a short time | `poll()` is not called often enough, or a `delay()` blocks it. |
| Two boards keep disconnecting each other | Both use the same client ID. |
| Publishing works but nothing is received | The subscription was not repeated after a reconnect, or the topic strings differ in case. |
| Garbled or truncated payloads | The callback did not read all available bytes. |
Exercise
Your board connects to the broker and publishes fine for about a minute, then the broker closes the connection. The loop contains mqttClient.poll(); followed by delay(90000); before the next publish. What is wrong, and how do you fix it?
Show answer
The 90-second delay stops poll() from running, so no keep-alive pings are sent and the broker treats the client as dead. Replace the delay with millis()-based timing, as in the publish sketch, so poll() runs on every pass through loop(). The fix does not depend on how long the delay is, as long as it exceeds the keep-alive window.
Exercise
After a Wi-Fi outage, your subscriber sketch reconnects to the broker successfully, but it no longer receives any messages. It calls subscribe() only in setup(). Why does this happen, and where should the call go?
Show answer
The broker discards the client's subscriptions when the connection ends, because the session is clean by default. After reconnecting, the board is connected but subscribed to nothing. Call subscribe() immediately after every successful connect(), for example inside the reconnect function.