This article is an example of using the Arduino framework’s NTP and TimeLib libraries with either the ESP-01s (Figure 1) or esp8266 to report the current time via the web served by the esp8266, which in this example is called NTPClient and TimeLib libraries. An Internet connection is required to read the date and time from an NTP provider such as time.nist.gov.

(Figure. 1 ESP-01s on dCore-0 v.0.7)

Equipment

The equipment for this experiment is ESP-01s or ESP-01 modules with chip programming and chip usage. We use the developed dCore-0 version 0.7 or the NodeMCU.

NTPClient

Using NTP, or Network Time Protocol, a protocol for reading network date and time values, allows the machines on the network to have the correct or least erroneous time. Also, being a UDP-based protocol, it is very fast to communicate, so calling the NTPClient library requires a header file:

#include <NTPClient.h>

#include <WiFiUdp.h>

To create an NTP object to use as a working reference:

WiFiUdp udp;

NTPClient obj( udp, “ntp”, time, time_interval )

The machine name of the main NTP service source is time.nist.gov. The interval value is a value indicating the number of seconds from Greenwich time. Therefore, when used in Thailand, it is 7*3600 or GMT+7. The list of NTP providers within Thailand is:

  1. 1.th.pool.ntp.org
  2. asia.pool.ntp.org
  3. 1.asia.pool.ntp.org
  4. time.navy.mi.th (Thailand Standard Time by Hydrographic Department, Royal Thai Navy)
  5. time2.navy.mi.th (Thailand Standard Time by Hydrographic Department, Royal Thai Navy)

The commands that can be used are as follows.

  1. obj.begin() start NTPClient
  2. obj.update() sync
  3. variable = obj.getEpochTime() read datetime in UNIX format and store in variable

TimeLib

The following commands can be used as follows: We use Paul Stoffregen‘s Time Library or TimeLib.h on GitHub as a library for converting DateTime data in NTPClient format. It must be downloaded from GitHub and copied it to the libraries folder of Arduino, then run it by importing the TimeLib.h file as follows:

#include <TimeLib.h>

The commands are

  1. hour() for reading hourly data which has a range of values 0 to 23.
  2. minute() for reading minutes which has a value range of 0 to 59.
  3. second() for reading the second value which has a value range of 0 to 59.
  4. day() for reading date data which has a range of values 1 to 31
  5. weekday() for reading day data which has a range of values 1 to 7
  6. month() for reading month data, it has a range of 1 to 12.
  7. year() for reading the year value in B.E.
  8. hourFormat12() To set the working hour format to 12 hours.
  9. isAM() to check the hour read are after midnight and before noon.
  10. isPM() to check the hour readings are after noon and before midnight.
  11. now() for reading the current time value
  12. setTime() to set date and time from time_t value
  13. adjustTime() for setting the date and time
  14. timeStatus() for reading time sync flag information which returns a
    1. timeNotSet means that date and time were never set.
    2. timeNeedsSync  means that a date and time sync must be performed.
    3. timeSet means the date and time are set and synced.
  15. setSyncProvider() for assigning external date and time values.
  16. setSyncInterval() for setting the duration of the date and time sync.

Example Code

Example program for connecting and reading date/time values from time.nist.gov and store the DateTime string in the dateMsg and timeMsg variables as follows

#include <ESP8266WiFi.h>
#include <WiFiUdp.h>
#include <NTPClient.h>
#include <TimeLib.h>

const char *ssid     = "ชื่อap";
const char *password = "รหัสของap";

WiFiUDP ntpUDP;


NTPClient timeClient(ntpUDP, "time.nist.gov", 7 * 3600, 60000);
unsigned long unix_epoch;
char dateMsg[64];
char timeMsg[64];

void setup() {
  Serial.begin(115200);

  WiFi.begin(ssid, password);
  while ( WiFi.status() != WL_CONNECTED ) {
    delay(500);
    Serial.print(".");
  }
  timeClient.begin();
}

void showRTC() {
  char dow_matrix[7][10] = {"SUNDAY", "MONDAY", "TUESDAY", "WEDNESDAY", "THURSDAY", "FRIDAY", "SATURDAY"};
  byte x_pos[7] = {29, 29, 23, 11, 17, 29, 17};
  static byte previous_dow = 0;

  if ( previous_dow != weekday(unix_epoch) )   {
    previous_dow = weekday(unix_epoch);
  }

  sprintf( dateMsg, "%02u-%02u-%04u", day(unix_epoch), month(unix_epoch), year(unix_epoch) );
  sprintf( timeMsg, "%02u:%02u:%02u", hour(unix_epoch), minute(unix_epoch), second(unix_epoch) );
  Serial.println(dateMsg);
  Serial.println(timeMsg);

}

void loop() {
  timeClient.update();
  unix_epoch = timeClient.getEpochTime();   // get UNIX Epoch time

  showRTC();
  delay(500);
}

When applied to the microcontroller esp8266 as an AP provider and when accessing the chip’s web, it reports the date and time as shown in Figure 2.

(Figure. 2 The results when applied to AP and web service)

Conclusion

From this article, you will find that esp8266 or ESP-01/ESP-01s family makes it easy to access NTP services. Therefore, when developing a system related to date and time, values ​​that correspond to a given country can be accessed. This can be applied to a data logger that collects values ​​from sensors and records the values ​​according to the specified date and time without having to install additional circuits of the RTC kit. Finally, have fun with programming.

If you want to talk with us, feel free to leave comments below!!

References

  1. Paul Stoffregen : Time
  2. ThaiCERT : NTP Reflection DDoS attack

(C) 2020-2021, By Jarut Busarathid and Danai Jedsadathitikul

Updated 2021-11-29