NTPClient Arduino Library

repository·master·Indexed 20 days ago

https://github.com/arduino-libraries/ntpclient

An Arduino library that enables microcontrollers to synchronize internal clocks with Network Time Protocol (NTP) servers over UDP. It supports custom NTP server addresses, time offsets, and update intervals, and provides methods like getEpochTime() to retrieve the Unix epoch.

Tokens
605
Snippets
2
Records
2
Agent score
20%

What's inside NTPClient

  1. Connect to an NTP server

    master

    To 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);
    }
  2. Get the Unix epoch time with getEpochTime()

    master

    The getEpochTime() method returns the Unix epoch, representing the total seconds elapsed since 00:00:00 UTC on 1 January 1970. Note that leap seconds are ignored, and every day is treated as having exactly 86400 seconds.

    Attention: If you have configured a time offset in the NTPClient constructor, that offset will be added to the returned epoch timestamp.

    // Returns seconds since 1 Jan 1970 (including configured offset)
    long epochTime = timeClient.getEpochTime();