Sub topic 9
Messaging with MQTT
Prerequisites and the MQTT model
This chapter assumes that you can upload an Arduino sketch, use Serial, connect the board to Wi-Fi, and read its IP address. It also assumes that you know basic network terms such as port and router.
MQTT is a lightweight messaging protocol for devices with limited memory or bandwidth. Instead of connecting directly to every other device, each device connects to a broker. The broker receives messages and forwards them to interested clients.
A topic is a named channel, such as home/office/temperature. A client can publish a message to a topic, subscribe to a topic, or do both.
The broker does not normally interpret the message. It matches the topic and forwards the payload. This makes MQTT useful when several devices need the same data.
Publish and subscribe
Publishing is sending a payload to a topic. Subscribing tells the broker which topics the client wants to receive. A client may subscribe before it publishes, after it publishes, or only perform one of these actions.
The ArduinoMqttClient library uses a network client underneath. For an unencrypted local connection, that client is WiFiClient. The poll() call is important because it lets the library process incoming packets and maintain the connection.
Create an arduino_secrets.h file beside the sketch:
#define SECRET_SSID "your-network-name"
#define SECRET_PASS "your-password"The following sketch publishes uptime every five seconds and prints messages received on demo/commands.
#include <WiFiNINA.h>
#include <ArduinoMqttClient.h>
#include "arduino_secrets.h"
WiFiClient wifiClient;
MqttClient mqttClient(wifiClient);
const char broker[] = "broker.example.com";
const int brokerPort = 1883;
const char publishTopic[] = "demo/uptime";
const char subscribeTopic[] = "demo/commands";
unsigned long lastPublish = 0;
void onMessage(int messageSize) {
Serial.print("Message on ");
Serial.println(mqttClient.messageTopic());
while (mqttClient.available()) {
Serial.write(mqttClient.read());
}
Serial.println();
}
void setup() {
Serial.begin(115200);
while (!Serial && millis() < 5000) {}
while (WiFi.begin(SECRET_SSID, SECRET_PASS) != WL_CONNECTED) {
Serial.println("Wi-Fi connection failed; retrying");
delay(5000);
}
mqttClient.onMessage(onMessage);
if (!mqttClient.connect(broker, brokerPort)) {
Serial.print("MQTT connection failed, error ");
Serial.println(mqttClient.connectError());
while (true) {}
}
mqttClient.subscribe(subscribeTopic);
Serial.println("Connected and subscribed");
}
void loop() {
mqttClient.poll();
if (millis() - lastPublish >= 5000) {
lastPublish = millis();
mqttClient.beginMessage(publishTopic);
mqttClient.print(millis() / 1000);
mqttClient.endMessage();
Serial.println("Published uptime");
}
}Replace broker.example.com with the hostname or IP address of an MQTT broker that you are authorized to use. The broker must be reachable from the Arduino's network, and port 1883 is commonly used for an unencrypted MQTT connection.
When a message arrives, the library calls onMessage. The messageSize argument tells you how many bytes are in the payload. The example reads until no bytes remain. For structured data, you could read the payload into a buffer and parse JSON, but always enforce a maximum size before storing incoming data.
Delivery and connection errors
MQTT supports delivery quality levels called QoS:
| QoS | Meaning | Typical use |
|---|---|---|
| 0 | Deliver at most once | Frequent sensor readings |
| 1 | Deliver at least once, so duplicates are possible | Important commands |
| 2 | Deliver exactly once, with more overhead | Rare operations requiring strict delivery |
The default library calls commonly use QoS 0. At this level, a lost connection can lose a message. QoS 1 improves delivery but requires the receiver to tolerate duplicate messages. Design commands to be safe if they are repeated.
poll() does not automatically make an application reliable after every network failure. In a longer-running device, check mqttClient.connected() and reconnect at controlled intervals. Avoid reconnecting in a tight loop, because repeated attempts can prevent sensor readings and other work from running.
Exercise
Exercise
Why must the sketch call mqttClient.poll() repeatedly instead of calling it only after publishing?
Show answer
poll() processes incoming packets and services the MQTT connection. Calling it only after publishing can delay or miss incoming messages and may allow the connection to time out.