🛠 Publier en MQTT sur le réseau cellulaire
Objectives
Publish measurements to an MQTT broker via the NB-IoT/LTE-M connection, combining the MKRNB library (network access) and PubSubClient (MQTT protocol). This is the typical use case for a sensor on an isolated site.
Hardware
- 1 MKR NB 1500 board + antenna + data SIM card (see the attachment tutorial)
- A reachable MQTT broker: for testing, use
test.mosquitto.orgon port 1883 (unencrypted, do not send sensitive data) - Arduino library PubSubClient (Nick O'Leary) installed via the library manager
Complete code
// Publication MQTT sur NB-IoT/LTE-M — MKR NB 1500
#include <MKRNB.h>
#include <PubSubClient.h>
#include "arduino_secrets.h"
const char PINNUMBER[] = SECRET_PINNUMBER;
const char APN[] = "orange";
const char BROKER[] = "test.mosquitto.org";
const int PORT = 1883;
const char TOPIC[] = "mkrnb1500/donnees";
NB nbAccess;
GPRS gprs;
NBClient netClient; // socket TCP via le modem
PubSubClient mqtt(netClient);
unsigned long dernierEnvoi = 0;
void setup {
Serial.begin(9600);
while (!Serial);
bool ok = false;
while (!ok) {
if ((nbAccess.begin(PINNUMBER) == NB_READY) &&
(gprs.attachGPRS(APN) == GPRS_READY)) ok = true;
else delay(2000);
}
mqtt.setServer(BROKER, PORT);
mqtt.setKeepAlive(120); // keepalive adapte a la latence cellulaire
while (!mqtt.connect("mkrnb-1")) delay(5000);
}
void loop {
mqtt.loop;
if (millis - dernierEnvoi > 60000) { // 1 message par minute
dernierEnvoi = millis;
int v = analogRead(A0);
char buf[48];
snprintf(buf, sizeof(buf), "{\"a0\":%d,\"rssi_ok\":1}", v);
mqtt.publish(TOPIC, buf);
Serial.println(buf);
}
}
Expected verification
From another machine: mosquitto_sub -h test.mosquitto.org -t 'mkrnb1500/donnees' displays a JSON message every minute. The published payload is also displayed on the serial console.
Common errors
mqtt.connectfails without details: a frequent cause is an unreachable broker from the operator's network (firewall, blocked port on an IoT plan) or a keepalive interval that is too short combined with the module's PSM.- Forgetting
gprs.attachGPRS(APN): the TCP client cannot open anything without a packet context. - PubSubClient is limited to 256 bytes by default: call
mqtt.setBufferSizefor large messages. - NB-IoT networks with high latency: plan for generous timeouts and clean reconnections (
mqtt.disconnectthenconnect). - This topic is frequently documented on the Arduino forum: MQTT/NB-IoT issues stem from TCP/keepalive, not the board itself.
Other tutorials for this board
Code examples for this board
attente-lte-nbiot.inoArduinochoix-bande.inoArduinopublish-mqtt-minimal.inoArduinoeconomie-energie.inoArduinogeoloc-cellules.inoArduinotest-coverage.inoArduino