reconnexion-rapide.ino

Arduino MKR NB 1500 · File : reconnexion-rapide.ino · Language : Arduino · Use case : Se réattacher au réseau sans pleine réinitialisation

On the move or underground, the cell vanishes then returns: instead of a 30-second full reboot, this sketch re-polls radio attach every two seconds and only resets the MKR NB 1500 modem as a last resort. The IP session resumes faster.

Hardware

An Arduino MKR NB 1500 (SAMD21 microcontroller, u-blox LTE-M/NB-IoT modem, external antenna, LiPo power on J6 or USB). IoT SIM, antenna fitted, reachable destination server.

Wiring

No wiring; fully autonomous behaviour after flashing, suited to sealed enclosures.

How it works

getStatus() polls the network stack without touching the PDP session; attachGPRS is only replayed once coverage returns. The full restart becomes the exception, sparing battery and signalling budget.

Running it

Install the Arduino SAMD Boards package and the MKRNB library, select the board, upload. Plan for an activated IoT SIM (LTE-M or NB1) and good reception: attaching to the network can take several minutes.

Variants

Add a hardware watchdog (modem RESET pin driven by a GPIO) if your location suffers firmware lock-ups.

reconnexion-rapide.ino

// Reconnexion rapide : garder la session IP et reattacher vite.
// Le SARA-R4 supporte "attache rapide" si la session est conservee.
#include <MKRNB.h>

const char PIN_SIM[] = "0000";
const char APN[] = "iot.1nce.net";

NB nb;
NBClient client;

bool reseauHorsLigne() {
  return nb.getStatus() != NETWORK_JOINED;
}

void setup() {
  Serial.begin(9600);
  if (nb.begin(PIN_SIM) != NB_READY) while (true);
  while (reseauHorsLigne()) delay(2000);
  nb.attachGPRS(APN);
}

void loop() {
  if (reseauHorsLigne()) {
    Serial.println(F("Reseau perdu, reattachement..."));
    int essai = 0;
    while (reseauHorsLigne() && essai++ < 30) delay(2000);
    if (reseauHorsLigne()) {
      nb.restart(); // dernier recours (~30 s)
      while (reseauHorsLigne()) delay(2000);
    }
    nb.attachGPRS(APN);
  }
  // Publication toutes les 10 min
  static unsigned long dernierEnvoi = 0;
  if (millis() - dernierEnvoi >= 600000) {
    dernierEnvoi = millis();
    if (client.connect("192.0.2.10", 1883)) {
      client.print("nb1500/ok\n"); client.stop();
    }
  }
}

← Back to the board