Sub topic 3
Messaging with MQTT
This chapter assumes you can connect a board to Wi-Fi, read a sketch's setup() and loop() functions, use the Serial Monitor, and install libraries in the Arduino IDE. You also need access to an MQTT broker, which is a server that relays messages between devices.
Messaging with MQTT
MQTT (Message Queuing Telemetry Transport) is a lightweight publish and subscribe protocol. A device publishes messages to a topic, a text label such as demo/uptime, and the broker forwards them to every client subscribed to that topic. The board never needs to know the address of the receiving device.
#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();
}
}Serving a page from the board
A board can run a WiFiServer on port 80 and answer HTTP requests from devices on the same local network. Call server.begin() in setup(), then in loop() call server.available() to get a waiting client. Read and discard the request, write an HTTP/1.1 status line and headers, send the body, and call client.stop(). Anyone on your network can then open the board's IP address in a browser. The page is not reachable from the internet unless you configure your router to forward traffic to the board.
Staying connected without blocking
Wi-Fi can drop at any time. A delay() loop that waits for reconnection stops all other work. Instead, check the status on each pass and retry at a set interval using millis().
#include <WiFiNINA.h>
#include "arduino_secrets.h"
const unsigned long RETRY_INTERVAL_MS = 10000;
unsigned long lastAttempt = 0;
void ensureWifi() {
if (WiFi.status() == WL_CONNECTED) return;
if (millis() - lastAttempt < RETRY_INTERVAL_MS) return;
lastAttempt = millis();
Serial.println("Wi-Fi down, reconnecting");
WiFi.begin(SECRET_SSID, SECRET_PASS);
}
void setup() {
Serial.begin(115200);
WiFi.begin(SECRET_SSID, SECRET_PASS);
}
void loop() {
ensureWifi();
// Other work continues here, and network calls run only while connected.
}Securing a connected device
- Keep credentials in
arduino_secrets.hand add that file to.gitignore. - Use
WiFiSSLClienton port 443 for HTTPS and MQTT over TLS when the service supports it. - Use a unique, strong broker password, and never publish secrets to a topic.
- Limit the local web server to status pages. Do not expose control actions without authentication.
Troubleshooting connection problems
| Symptom | Likely cause | Fix |
|---|---|---|
| `WL_NO_MODULE` at startup | Wrong board or library | Install the library that matches your board, such as WiFiNINA |
| Stuck on "Connecting" | Wrong SSID or password, or a 5 GHz network | Check credentials and use a 2.4 GHz network |
| MQTT error after Wi-Fi connects | Wrong broker address, port, or credentials | Confirm the broker, port 1883 or 8883, and login details |
| Connection drops every few minutes | `poll()` not called, or a blocking `delay()` | Call `poll()` each loop and use `millis()` timing |
Exercise
The sketch publishes every 5 seconds. How would you change it to publish every 30 seconds, and why is millis() better than delay(30000) here?
Show answer
Change 5000 to 30000 in the if condition. Using millis() lets loop() keep calling mqttClient.poll(). A delay(30000) would block the loop, so the broker connection could time out.