Skip to content

uPesy now ships to the entire European Union

Contents Menu Expand Light mode Dark mode Auto light/dark mode

Get the exact date and time with an ESP32 from an NTP server with Arduino code

With a simple internet connection, it is possible to calibrate the internal clock of the ESP32 and thus have the time up to date. No need to have an external PSTN clock with a battery to keep the time up to date if you can retrieve it from the Internet. This is very useful when the ESP32 wakes up from time to time to communicate with WEB services and wants to date its packets with the correct date.

Note

However, an external RTC clock remains interesting if the ESP32 does not have direct access to the Internet. One can also use an NTP server to calibrate the RTC clock and correct its offset with time. 😉

NTP server: What is it for?

An NTP (Network Time Protocol) server is a server that synchronizes the clocks of different computers on a computer network. Their purpose is to ensure that all computers on the network have the same time, which is vital for many applications, such as file management or computer security. It also prevents errors caused by clocks that are not synchronized. The protocol is more complex than that because to obtain a clock accurate to the millisecond; it is necessary to consider the time that elapses during the sending of the requests and the processing time by the server.

If you want to learn more about the NTP protocol and its architecture, I recommend this excellent video from Computerphile .

Note

In our case, we will use it to synchronize the internal clock of the ESP32.

Many NTP server addresses can be used to synchronize the date. Although there are many others, the best known is "pool.ntp.org" .

What is the difference between Timestamp, Epoch time and Unix?

A timestamp is a time stamp that indicates an event’s precise date and time. It is a series of numbers representing the event’s date and time.

Epoch time, or Unix time, is a time reference commonly used in computer systems. It represents the number of seconds elapsed since January 1st, 1970, at midnight UTC . This reference date is often used as a starting point to calculate the date and time of an event using a timestamp. For example, if a timestamp is equal to 1601054743, it means that it is the number of seconds elapsed from January 1, 1970, until the event in question (i.e., Tuesday, December 13, 2022, at 10h12m25s). Its use facilitates the calculations related to the date and the hour in the computer systems.

Take into account the time difference (UTC, GMT)

To have the right time, we must consider the local time difference. To do this, we reference the UTC or GMT corresponding to the time difference +0. We then adjust this value according to the local time zone and possibly an additional summer/winter time. For France, it is +1 in winter and +2 in summer.

Recovering the date from the Internet (NTP server) with an ESP32

With Arduino code, this is very simple because there are basic functions that take care of it. No additional library is required; everything is integrated in time.h .

Here is a basic script that you need to fill in with the credentials of your Wi-Fi box: 🙂

#include <WiFi.h>
#include "time.h"

const char* ssid = "upesy-ap"; // Name of the Wi-Fi box
const char* password = "cupcakes"; // MDP of the Wi-Fi box

const char* ntpServer = "pool.ntp.org";
const long  gmtOffset_sec = 3600 * 1;
const int   daylightOffset_sec = 3600 * 0;

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

  WiFi.mode(WIFI_STA); // Optional
  WiFi.begin(ssid, password);
  Serial.println("\nConnecting");

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

  Serial.println("\nConnected to the WiFi network");
  Serial.print("Local ESP32 IP: ");
  Serial.println(WiFi.localIP());

  // We configure the NTP server
  configTime(gmtOffset_sec, daylightOffset_sec, ntpServer);
}

void loop() {
  struct tm timeinfo;
  if (!getLocalTime(&timeinfo)) {
    Serial.println("Failed to obtain time");
  }
  Serial.println(&timeinfo, "%A, %B %d %Y %H:%M:%S");
  delay(1000);
}

It can be broken down into three parts:

  • Wi-Fi configuration and connection

  • The configuration of the NTP server

  • Retrieving the date every second from the NTP server

Note

If you are in summer, you will have to put a daylightOffset_sec = 3600; to have daylight saving time.

In the serial monitor, the correct date is obtained

date retrieved from an ntp server

The most complicated part of the code is formatting the date in text from the timeinfo documentation (a timestamp). Here is a link to C++ documentation to know the correct parameters according to the final format.

You can display only the desired data, for example, minutes:

Serial.println(&timeinfo, "%M");

To get this value in a variable, we can use the following code:

char timeMinutes[3];
strftime(timeMinutes,3, "%H", &timeinfo);
Serial.println(timeMinutes);

Or get the minutes directly from the structure C++ (The members of the structure are listed in the documentation ):

int minutes = timeinfo.tm_min;
Serial.println(minutes);

Advanced stuff

Automatically change the summer/winter time with a timezone

Over the years, zones have been established that detail all the local time specificities. You must have come across them when configuring an electronic device with a massive list of possible zones

timezone list

The list we will use is available on GitHub . We are interested in the information on the right. For Europe/Paris it is CET-1CEST,M3.5.0,M10.5.0/3 . Using this timezone , the date will be automatically updated when the time changes from summer to winter.

This section is available to premium members only. You still have 83% to discover.

Subscribe for only 5$/month

Already subscribed? Sign in

We use cookies to make your visit to the site as pleasant as possible. Privacy Policy