🛠 Publier en MQTT sur le réseau GPRS

Arduino MKR GSM 1400 · avance · Schéma : IMG-mkr-gsm-1400-avance-1-mkrgsm-mqtt-gprs.svg — MKR GSM 1400 publiant des messages MQTT via l'antenne vers un broker sur Internet, le flux traversant l'antenne relais et un serveur, avec jauges de capteur publiées.

Objectives

Connect the MKR GSM 1400 to an MQTT broker by stacking PubSubClient on top of GSMClient: since the MKRGSM client class mimics Arduino's Client class, PubSubClient works without modification. This is a typical pattern for field sensors (Irriduo irrigation, water monitoring): periodic reading, QoS 1 publication, and robust reconnection after radio outages.

Hardware

Complete Code

#include <MKRGSM.h>
#include <PubSubClient.h>
#include "arduino_secrets.h"
const char PINNUMBER[]     = SECRET_PINNUMBER;
const char GPRS_APN[]      = SECRET_GPRS_APN;
const char GPRS_LOGIN[]    = SECRET_GPRS_LOGIN;
const char GPRS_PASSWORD[] = SECRET_GPRS_PASSWORD;
const char MQTT_BROKER[]   = "broker.example.org";

GSMClient  netClient;
GPRS       gprs;
GSM        gsmAccess;
PubSubClient mqtt(netClient);

uint32_t dernierePub = 0;

void connexion {
  while (gsmAccess.begin(PINNUMBER) != GSM_READY) delay(2000);
  while (gprs.attachGPRS(GPRS_APN, GPRS_LOGIN, GPRS_PASSWORD) != GPRS_READY)
    delay(2000);
  mqtt.setServer(MQTT_BROKER, 1883);
  mqtt.setBufferSize(256);
  while (!mqtt.connect("mkr1400-capteur")) {
    Serial.print("MQTT rc="); Serial.println(mqtt.state);
    delay(5000);
  }
  Serial.println("MQTT connecte");
}

void setup {
  Serial.begin(9600);
  while (!Serial) {}
  connexion;
}

void loop {
  if (!mqtt.connected || !gprs) {   // coupure radio ou broker
    Serial.println("Reconnexion...");
    gsmAccess.shutdown;
    connexion;
  }
  mqtt.loop;                        // indispensable : trafic + keepalive
  if (millis - dernierePub > 60000UL) {
    dernierePub = millis;
    int v = analogRead(A1);           // exemple : capteur analogique
    char trame[48];
    snprintf(trame, sizeof trame, "{\"a1\":%d}", v);
    mqtt.publish("maison/mkr1400/a1", trame, true);  // retain
  }
  delay(100);
}

Expected Verification

mosquitto_sub -t 'maison/mkr1400/a1' (or your broker's client) receives a JSON frame every minute, even after moving the board to an area without network coverage: the reconnection loop resumes automatically. mqtt.loop must be called frequently — its absence causes keepalive disconnections and unprocessed incoming messages.

Common Errors

Other tutorials for this board

Code examples for this board

← Back to the board 🛠 All tutorials