Home » ESP32 Network Time Protocol example

ESP32 Network Time Protocol example

by shedboy71

Sometimes it is useful in any logging or displaying data to have a reasonably accurate time, by adding the NTPClient library you can do this quite easily

Add support for the NTPClient library by doing the following

  • Go To Library Manager and search for “NTP”
  • Locate and Install NTPClient Library from Fabrice Weinberg

In the example below I am GMT, so no time zone offset

Code

[cpp]

#include <WiFi.h>
const char* ssid = “username”;
const char* password = “password”;

/* Time Stamp */
#include <NTPClient.h>
#include <WiFiUdp.h>

#define NTP_OFFSET 0 * 60 * 60 // In seconds
#define NTP_INTERVAL 60 * 1000 // In miliseconds
#define NTP_ADDRESS “0.pool.ntp.org”

WiFiUDP ntpUDP;
NTPClient timeClient(ntpUDP, NTP_ADDRESS, NTP_OFFSET, NTP_INTERVAL);

void setup()
{
Serial.begin(115200);
Serial.println(“”);
Serial.println(“Time Stamp example”);
Serial.println(“”);
Serial.print(“Connecting to “);
Serial.println(ssid);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED)
{
delay(500);
Serial.print(“.”);
}
Serial.println(“”);
Serial.println(“WiFi connected.”);
Serial.println(“IP address: “);
Serial.println(WiFi.localIP());
timeClient.begin();

}

void loop()
{
timeClient.update();
String formattedTime = timeClient.getFormattedTime();
Serial.println(formattedTime);
delay(1000);
}

[/cpp]

 

Output

Open the serial monitor and check the clock on your PC/Mac (whatever)

22:32:01
22:32:02
22:32:03
22:32:04
22:32:05
22:32:06
22:32:07
22:32:08
22:32:09
22:32:10

 

Links

i could go into great detail about NTP but these sites do it better

https://en.wikipedia.org/wiki/Network_Time_Protocol

http://tf.nist.gov/tf-cgi/servers.cgi

You may also like

Leave a Comment

Adblock Detected

Please support us by disabling your AdBlocker extension from your browsers for our website.