heure-gsm.ino

Arduino MKR GSM 1400 · File : heure-gsm.ino · Language : Arduino · Use case : Récupérer l'heure réelle via le réseau cellulaire

Software real-time clock for a standalone station: the MKR GSM 1400 queries an HTTP server whose headers carry the time, then maintains the epoch locally with millis(). Essential for time-stamping offline measurements.

Hardware

An Arduino MKR GSM 1400 (SAMD21 microcontroller, 2G/GPRS cellular modem, external antenna, powered by a LiPo battery on the J6 connector or over USB). 2G data SIM and antenna; no sensor required for this example.

Wiring

No wiring; the example runs with the bare board over USB, indoors with decent 2G reception.

How it works

The HTTP reply contains a Date: header in RFC 1123 format. After syncing, the base epoch is stored with the current millis() value, yielding a precise derived clock between re-synchronisations.

Running it

In the Arduino IDE, install the Arduino SAMD Boards package, select the MKR GSM 1400 board, then upload. Network examples assume an active data SIM is inserted, the antenna is screwed on, and 2G coverage still exists in your area.

Variants

Use the network-provided time via AT+CMGL, or a real UDP/123 NTP client with GSMUDP if your operator allows that port.

heure-gsm.ino

// Heure reelle via GPRS : requete HTTP Date vers un serveur de temps.
#include <MKRGSM.h>

const char PIN_SIM[] = "0000";
const char APN[] = "sl2g";

GSM gsm; GSMGPRS gprs; GSMClient client;
unsigned long baseMs, heureEpoch; // epoch + millis() a la synchro

void setup() {
  Serial.begin(9600);
  if (gsm.begin(PIN_SIM) != GSM_READY) while (true);
  while (gsm.waitNetworkReady(30) != ON_NET);
  gprs.attachGPRS(APN, GPRS_AUTOMATIC_BEARER, 1);
  if (client.connect("ipv4.api.chronie.fr", 80)) {
    client.print("GET / HTTP/1.1\r\nHost: ipv4.api.chronie.fr\r\n\r\n");
    String entete = "";
    delay(1500); // laisser la reponse arriver sur le reseau 2G
    while (client.available() && entete.length() < 400)
      entete += (char)client.read();
    client.stop();
    int p = entete.indexOf("Date: ");
    if (p >= 0) Serial.println(entete.substring(p, p + 31));
    // convertir la date HTTP en epoch ; exemple fixe pour demo :
    heureEpoch = 1735689600UL;
    baseMs = millis();
  }
}

void loop() {
  Serial.println(String(heureEpoch + (millis() - baseMs) / 1000));
  delay(1000);
}

← Back to the board