Connect to a NTP server
Go to file
zeflo a225c1cc83
Update NTPClient.cpp
Until now the fraction of the second was not taken into account. Therefore the resulting time offset is up to 1000 ms. Using the provided Information increases the accuracy of the synchronization to 20-30 milliseconds. And it requires just two lines of code.

https://imgur.com/a/aVjvHON
In this plot both methods are compared. Plotted is the time difference in respect to a PPS signal provided by a GPS receiver.  For comparison the time was synchronized over 1000 times and the resulting time difference filled into the respective histogram.
2021-03-04 17:35:14 +01:00
examples Added functions for changing the timeOffset and updateInterval later 2016-05-14 12:04:18 +02:00
.travis.yml Initial add travis arduino build tests 2016-04-18 21:21:41 +02:00
CHANGELOG Update CHANGELOG 2016-05-31 16:33:15 -04:00
keywords.txt Update keywords.txt 2018-07-11 08:05:00 -04:00
library.json Version 3.1.0 2016-05-31 16:33:31 -04:00
library.properties Releasing v3.2.0 2019-09-18 10:01:20 +02:00
NTPClient.cpp Update NTPClient.cpp 2021-03-04 17:35:14 +01:00
NTPClient.h Adding default port range (#117) 2020-09-07 17:14:47 +02:00
README.md Adding documentation of function 'getEpochTime' to README 2019-09-19 07:32:17 +02:00

NTPClient

Build Status

Connect to a NTP server, here is how:

#include <NTPClient.h>
// change next line to use with another board/shield
#include <ESP8266WiFi.h>
//#include <WiFi.h> // for WiFi shield
//#include <WiFi101.h> // for WiFi 101 shield or MKR1000
#include <WiFiUdp.h>

const char *ssid     = "<SSID>";
const char *password = "<PASSWORD>";

WiFiUDP ntpUDP;

// By default 'pool.ntp.org' is used with 60 seconds update interval and
// no offset
NTPClient timeClient(ntpUDP);

// You can specify the time server pool and the offset, (in seconds)
// additionaly you can specify the update interval (in milliseconds).
// 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);
}

Function documentation

getEpochTime returns the unix epoch, which are the seconds elapsed since 00:00:00 UTC on 1 January 1970 (leap seconds are ignored, every day is treated as having 86400 seconds). Attention: If you have set a time offset this time offset will be added to your epoch timestamp.