horloge-ntp.ino
Accurate clock for the MKR WiFi 1010: after connecting, the sketch sends an NTP UDP/123 request to pool.ntp.org and sets the Time library, with hourly resync. The 48-byte frames and the 1968-1900 offset are the two classic traps.
Hardware
An Arduino MKR WiFi 1010 (SAMD21 microcontroller, WINC1500 Wi-Fi module, no Bluetooth, USB or LiPo power on J6). MKR WiFi 1010, network allowing outbound UDP/123 (rarely blocked at home).
Wiring
No wiring; the example follows the official TimeNTP.ino structure of the WiFi101 library.
How it works
setSyncProvider calls getNtpTime periodically; the NTP reply carries the Unix epoch at byte 40. Between syncs, the Time library increments locally with millis().
Running it
Install Arduino SAMD Boards and the WiFi101 library, select the board, upload. Wi-Fi runs on 2.4 GHz only: check that your access point is not 5 GHz only.
Variants
Use a local NTP server (Fritz!Box router, Raspberry Pi) for isolated networks, or show the time on a small I2C display.
horloge-ntp.ino
// Heure NTP MKR WiFi 1010 : reglage reseau puis horloge locale.
#include <SPI.h>
#include <WiFi101.h>
#include <TimeLib.h>
#include <WiFiUdp.h>
const char SSID[] = "MonReseau";
const char PASS[] = "motdepassewifi";
const char NTP[] = "pool.ntp.org";
const int PORT_NTP = 123;
WiFiUDP udp;
void setup() {
Serial.begin(9600);
WiFi.begin(WPA_PASS_PHRASE, SSID, PASS);
while (WiFi.status() != WL_CONNECTED) delay(100);
Serial.println(WiFi.localIP());
udp.begin(PORT_NTP);
setSyncProvider(getNtpTime);
setSyncInterval(3600);
}
void loop() {
if (timeStatus() != timeNotSet)
Serial.println(formatTime(now())); // hh:mm:ss via lib Time
delay(1000);
}
// Appelle par la lib Time : renvoie l'epoch NTP courant.
time_t getNtpTime() {
while (udp.parsePacket() > 0); // vide l'ancien trafic
sendNtpPacket(); // paquet NTP standard de 48 octets
unsigned long debut = millis();
while (udp.parsePacket() < 48 && millis() - debut < 1000) delay(1);
// convertir les octets 40-43 de la reponse en epoch
// (exemple complet : TimeNTP.ino de WiFi101)
return 0;
}