Connect to an NTP server
masterTo use NTPClient, you must provide a WiFiUDP object to the NTPClient constructor. The library requires an active network connection (e.g., via ESP8266WiFi or WiFi libraries) to communicate with NTP servers.
By default, the client uses pool.ntp.org as the server, has a 60-second update interval, and no time offset. You can customize these settings by providing a specific NTP server address, a time offset in seconds, and an update interval in milliseconds.
#include <NTPClient.h>
#include <ESP8266WiFi.h>
#include <WiFiUdp.h>
const char *ssid = "<SSID>";
const char *password = "<PASSWORD>";
WiFiUDP ntpUDP;
// Default: pool.ntp.org, 60s interval, 0 offset
NTPClient timeClient(ntpUDP);
// Custom: specific server, 3600s offset, 60000ms interval
// NTPClient timeClient(ntpUDP, "europe.pool.ntp.org", 3600, 60000);
void setup(){
Serial.begin(115200);
WiFi.begin(ssid, password);
while ( WiFi.status() != WL_CONNECTED ) {
delay ( 500 );
Serial.print ( "." );
}
timeClient.begin();
}
void loop() {
timeClient.update();
Serial.println(timeClient.getFormattedTime());
delay(1000);
}