🛠 Publier en MQTT sur le réseau cellulaire

Arduino MKR NB 1500 · intermediaire · Schéma : IMG-mkr-nb-1500-intermediaire-2-mkrnb-mqtt-cellulaire.svg — MKR NB 1500 reliée par ondes à un routeur cellulaire puis à un serveur MQTT, avec le topic mkrnb1500/donnees et un message JSON

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

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

Other tutorials for this board

Code examples for this board

← Back to the board 🛠 All tutorials