How to get the current time from an NTP Server using an Arduino, ESP32, or ESP8266 [shorts #4]

Arduino-based clock projects are a staple in the maker and DIY community, and I’ve built a few ones myself. Such projects typically incorporate a real-time clock (RTC) module that keeps track of the time. However, once the battery on the RTC module runs flat, it forgets the previously set time. Another option involves adding a few push buttons to allow users to set the time. The Arduino itself keeps track of the time as long as it’s plugged into a power supply, and it forgets the settings once you disconnect it from the power source. This short article discusses a third option that allows you to make your clock projects much more user-friendly by automatically setting and adjusting the time when necessary.

You can accomplish this by using an IoT-capable Arduino board and contacting an NTP server to request the current time from the server.

A short overview of NTP

The network time protocol (NTP) consists of numerous decentralized computers that keep track of the time and communicate it to other participants when necessary. The hierarchy is organized in various layers referred to as stratum levels. Stratum zero devices are at the top of the hierarchy. This layer contains high-precision timing devices such as an atomic clock. Stratum 1 contains computers that are directly (physically) connected to the high-precision clocks on level 0. Each computer in a stratum layer synchronizes its time with the layer above and propagates the change to the layers below. Eventually, you can use any connected device to request the most current time from a computer in the network.

How to use an Arduino to request the time from an NTP server

First, install the NTPClient library using the Arduino IDE’s built-in library manager:

Figure 1: Install the NTPClient library using the Arduino IDE’s built-in library manager

Then, you can utilize the freshly installed library to request the time from an NTP server. The following short Arduino sketch establishes a UDP connection to the NTP pool. This pool automatically selects the best server based on your location. The script then requests the time once a second and displays the result on the Arduino IDE’s serial console:

#include <WiFiNINA.h>
#include <WiFiUdp.h>
#include <NTPClient.h>

#define SSID "REPLACE_ME"
#define PASS "WIFI_PASS"

const long utcOffsetWinter = 3600; // Offset from UTC in seconds (3600 seconds = 1h) -- UTC+1 (Central European Winter Time)
const long utcOffsetSummer = 7200; // Offset from UTC in seconds (7200 seconds = 2h) -- UTC+2 (Central European Summer Time)
unsigned long lastupdate = 0UL;

// Define NTP Client to get time
WiFiUDP udpSocket;
NTPClient ntpClient(udpSocket, "pool.ntp.org", utcOffsetWinter);

void setup()
{
  Serial.begin(9600);
  WiFi.begin(SSID, PASS);

  Serial.print("Connecting to ");
  Serial.print(SSID);

  while (WiFi.status() != WL_CONNECTED)
  {
    Serial.print(".");
    delay(250);
  }

  Serial.println(" Done!");
  
  ntpClient.begin();
}

void loop()
{
  unsigned long currentMillis = millis();

  if(currentMillis - lastupdate > 1000)
  {
    ntpClient.update();
    
    Serial.print(ntpClient.getHours());
    Serial.print(":");
    Serial.print(ntpClient.getMinutes());
    Serial.print(":");
    Serial.println(ntpClient.getSeconds());

    lastupdate = currentMillis;
  }
}

Note that this code works on Arduino boards that use the WiFiNINA module. Some examples include the Arduino RP2040 Connect and the Arduino Nano 33 IoT. When using an ESP8266, make sure to replace the first line of the code snippet with:

#include <ESP8266WiFi.h>

Lastly, here’s a screenshot of the Arduino sketch in action:

Figure 2: You should see something like this when you execute the script from above.

Summary

You can use the NTP when building an Arduino-based clock project to save a few external components. Furthermore, the users won’t have to mess around with physical buttons to set the time whenever the Arduino loses power. NTP is a decentralized network of computers that you can employ to get the current time.

Leave your two cents, comment here!

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.