Sub topic 11
Staying connected without blocking
This chapter assumes you can already connect a WiFiNINA board to a network (as in the earlier chapters) and that you know the millis() timing pattern. It also assumes you have run the MQTT publishing sketch. The examples target boards such as the MKR WiFi 1010 or Nano 33 IoT.
Why connections drop
A connected board can lose its link at any time. Common causes:
- The access point reboots or changes channel.
- The signal weakens because someone moved the board or closed a door.
- The router's DHCP lease expires and the renewal fails.
- The MQTT broker restarts or closes idle sessions.
- The server closes a TCP connection that has been quiet for too long.
A sketch that connects once in setup() and never checks again works on the bench and fails in the field. A deployed sketch has to assume every connection will eventually fail and must be able to recover without a human pressing reset.
There are two separate layers to watch:
| Layer | What breaks | How to detect it |
|---|---|---|
| Wi-Fi link | Association with the access point is lost | `WiFi.status() != WL_CONNECTED` |
| TCP or MQTT session | The connection to a server is gone, even though Wi-Fi is fine | `client.connected()` or `mqttClient.connected()` returns false |
Wi-Fi can be healthy while the broker session is dead, and the reverse is never useful. Check the lower layer first, then the upper one.
Why blocking code is a problem
The connection sketch earlier in this tutorial used this pattern:
while (status != WL_CONNECTED) {
status = WiFi.begin(SECRET_SSID, SECRET_PASS);
delay(10000);
}That is acceptable in setup() when the board has nothing else to do. It is a poor choice once the board has other jobs, such as reading a sensor, driving a motor, or watching a safety switch. While the loop waits, nothing else runs. If the router is off for ten minutes, the board does nothing for ten minutes.
Blocking happens in more places than your own delay(). WiFi.begin() can take several seconds to return while it waits for the module to associate. client.connect() waits on DNS and the TCP handshake and can stall for a long time when the server is unreachable. You cannot make those calls instant. You can make them rare, and you can avoid wrapping them in extra delays.
The approach in this chapter is to turn the connection into something the loop checks quickly on every pass. Most passes find everything healthy and return in microseconds. Only when something is down does the sketch spend time on a reconnect attempt, and then no more often than a set interval.
The basic non-blocking check
This is the pattern from the spine, shown as a complete sketch:
#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.
}Three details matter:
- Subtraction, not comparison of timestamps.
millis() - lastAttemptuses unsigned arithmetic, so it stays correct whenmillis()wraps around after about 49 days. Writingmillis() > lastAttempt + RETRY_INTERVAL_MSbreaks at the wrap. - Early returns. The function exits at the first reason not to act. A healthy connection costs one status read.
lastAttemptis updated before the call. IfWiFi.begin()takes five seconds, the next attempt is measured from when this one started. Set it after the call if you want the pause counted from when the attempt ended.
There is a quirk here: lastAttempt starts at 0, so if the first WiFi.begin() in setup() fails, the first retry happens roughly ten seconds after power-up, not immediately. That is usually fine.
The reconnection life cycle
The sketch moves through a small set of states. Naming them helps when you debug from Serial output.
You do not need to code these states as an enum. The status functions already tell you where you are. The diagram shows the rules the code must obey: the MQTT layer is only attempted when Wi-Fi is up, and any loss of Wi-Fi invalidates everything above it.
Backing off after repeated failures
A fixed ten-second retry has a flaw. If the broker is down for an hour, 360 attempts hit it, and many devices doing this at once can swamp a server as it comes back. The usual remedy is exponential backoff: double the wait after each failure up to a cap, and reset it on success.
The sketch below combines Wi-Fi recovery and MQTT recovery with backoff. The broker address is a placeholder.
#include <WiFiNINA.h>
#include <ArduinoMqttClient.h>
#include "arduino_secrets.h"
const unsigned long RETRY_MIN_MS = 2000;
const unsigned long RETRY_MAX_MS = 60000;
const unsigned long PUBLISH_INTERVAL_MS = 5000;
struct Retry {
unsigned long last = 0;
unsigned long wait = RETRY_MIN_MS;
bool started = false;
bool due() const { return !started || millis() - last >= wait; }
void attempted() { started = true; last = millis(); }
void backOff() { wait = min(wait * 2, RETRY_MAX_MS); }
void reset() { started = false; wait = RETRY_MIN_MS; }
};
WiFiClient wifiClient;
MqttClient mqttClient(wifiClient);
const char broker[] = "broker.example.com";
const int port = 1883;
const char topic[] = "demo/uptime";
Retry wifiRetry;
Retry mqttRetry;
unsigned long lastSend = 0;
bool ensureWifi() {
if (WiFi.status() == WL_CONNECTED) {
if (wifiRetry.started) {
wifiRetry.reset();
Serial.print("Wi-Fi up, IP ");
Serial.println(WiFi.localIP());
}
return true;
}
if (wifiRetry.due()) {
Serial.println("Wi-Fi down, reconnecting");
mqttClient.stop();
wifiRetry.attempted();
WiFi.begin(SECRET_SSID, SECRET_PASS);
wifiRetry.backOff();
}
return false;
}
bool ensureMqtt() {
if (mqttClient.connected()) {
mqttRetry.reset();
return true;
}
if (mqttRetry.due()) {
mqttRetry.attempted();
Serial.print("Connecting to MQTT broker... ");
if (mqttClient.connect(broker, port)) {
Serial.println("ok");
mqttRetry.reset();
return true;
}
Serial.print("failed, error ");
Serial.println(mqttClient.connectError());
mqttRetry.backOff();
}
return false;
}
void setup() {
Serial.begin(115200);
while (!Serial && millis() < 5000) {}
}
void loop() {
// Work that does not need the network goes here and always runs.
if (!ensureWifi()) return;
if (!ensureMqtt()) return;
mqttClient.poll();
if (millis() - lastSend >= PUBLISH_INTERVAL_MS) {
lastSend = millis();
mqttClient.beginMessage(topic);
mqttClient.print(millis() / 1000);
mqttClient.endMessage();
}
}How it works:
Retrybundles the timer, the current wait, and a flag for "no attempt yet". Each connection layer has its own instance, so a broker outage does not slow Wi-Fi retries.ensureWifi()callsmqttClient.stop()before reconnecting. This discards the old socket so the library does not try to reuse a session that died with the link.ensureMqtt()only runs after Wi-Fi is confirmed up, becauseloop()returns early otherwise.mqttClient.poll()runs on every healthy pass. It services keep-alive pings and incoming messages. If you stop calling it for longer than the keep-alive interval, the broker drops you.
The first call to WiFi.begin() happens inside ensureWifi(), so setup() no longer waits for a connection. The sketch is useful from the first instant, and the serial log shows the recovery.
Common errors
- Reconnect loops that nest. A
while (WiFi.status() != WL_CONNECTED) { ... delay(...); }inside a helper called fromloop()brings back the blocking you removed. Useif, and letloop()come around again. - Retrying faster than the module can respond. Calling
WiFi.begin()on every pass restarts the association before it finishes and can keep the board from ever connecting. Keep the minimum wait at a couple of seconds. - Forgetting the session layer. After a Wi-Fi outage the MQTT client may still believe it is connected until its next read or write fails. Calling
stop()when you restart Wi-Fi, as above, prevents stale state. - Checking
WiFi.status()once. The value is a snapshot. A call that follows a check can still fail, so handle a false return fromconnect()or a failed write, and do not assume success because the check passed. - Ignoring HTTP clients. For one-off requests, call
client.stop()once you finish, or afterconnected()returns false. Leaked sockets use up the module's small connection table, and laterconnect()calls begin to fail.
A last resort: resetting the board
Some failures leave the Wi-Fi module in a state that retries do not clear. A practical safeguard is a counter of consecutive failed attempts. When it passes a limit, such as ten, restart the board. On SAMD boards like the MKR WiFi 1010 and Nano 33 IoT, calling NVIC_SystemReset() does this. A hardware watchdog timer is the more robust option because it also covers a hung sketch, but its API differs between board families, so check your core's documentation.
Treat a reset as a last resort and log the reason before you reset, since a reboot loop is hard to diagnose later. Also remember that a reset loses any data held in RAM.
Exercise
In ensureWifi(), why is millis() - lastAttempt < RETRY_INTERVAL_MS safe across the roughly 49-day millis() rollover, while millis() < lastAttempt + RETRY_INTERVAL_MS is not?
Show answer
millis() and lastAttempt are unsigned long values, so the subtraction wraps modulo 2^32 and still gives the correct elapsed time after the rollover. In the second form, lastAttempt + RETRY_INTERVAL_MS can overflow and become a small number, or millis() can wrap back to a small number, so the comparison gives the wrong answer and the retry may fire constantly or never.
Exercise
Your sketch publishes over MQTT and also blinks a status LED every 500 ms. After a router outage, the LED stops blinking until the connection returns. Which change in loop() fixes this, and why?
Show answer
Move the LED code before the if (!ensureWifi()) return; line. The early returns skip everything after them while the network is down, so any work placed after them stops during an outage. Code that does not need the network must run before those checks.