Requirements
- Arduino IDE or VS Code with PlatformIO extension.
- ESP32 development board.
- USB data cable for connecting the board to your computer.
The core objective is to fetch and display real-time hours, minutes, and seconds via serial output.
Installing the NTPClient Libray
In PlatformIO, locate the NTPClient library using the library manager. Search for "NTPClient" and install the version by Fabrice Weinberg.
Basic Code Example
Below is a minimal sketch that connects to WiFi and prints the formatted time to the serial monitor.
#include <WiFi.h>
#include <WiFiUdp.h>
#include <NTPClient.h>
const char* networkName = "YourNetworkSSID";
const char* networkPass = "YourNetworkPassword";
WiFiUDP udpClient;
NTPClient ntpTime(udpClient);
void configureWiFi() {
WiFi.begin(networkName, networkPass);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
}
void setup() {
Serial.begin(115200);
configureWiFi();
ntpTime.begin();
}
void loop() {
ntpTime.update();
Serial.println(ntpTime.getFormattedTime());
delay(1000);
}
Advanced Implementation
This example provides a more comprehensive output, including date components, by parsing the Unix epoch time.
#include <WiFi.h>
#include <WiFiUdp.h>
#include <NTPClient.h>
WiFiUDP udpChannel;
NTPClient ntpHandler(udpChannel, "pool.ntp.org");
String dayNames[7] = {"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"};
String monthNames[12] = {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};
void initWiFi() {
const char* ssid = "YourNetworkSSID";
const char* pass = "YourNetworkPassword";
WiFi.mode(WIFI_STA);
WiFi.begin(ssid, pass);
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.print('.');
}
}
void initNTP() {
ntpHandler.begin();
// Set timezone offset in seconds (e.g., UTC+8 = 28800)
ntpHandler.setTimeOffset(28800);
}
void displayTimeData() {
ntpHandler.update();
unsigned long epochTime = ntpHandler.getEpochTime();
Serial.print("Epoch Timestamp: ");
Serial.println(epochTime);
Serial.print("Formatted HH:MM:SS: ");
Serial.println(ntpHandler.getFormattedTime());
Serial.print("Hour: ");
Serial.println(ntpHandler.getHours());
Serial.print("Minute: ");
Serial.println(ntpHandler.getMinutes());
Serial.print("Second: ");
Serial.println(ntpHandler.getSeconds());
Serial.print("Weekday: ");
Serial.println(dayNames[ntpHandler.getDay()]);
struct tm *timeInfo = gmtime((time_t *)&epochTime);
int dayOfMonth = timeInfo->tm_mday;
int monthNum = timeInfo->tm_mon + 1;
int year = timeInfo->tm_year + 1900;
Serial.print("Date (Y-M-D): ");
Serial.printf("%d-%02d-%02d\n", year, monthNum, dayOfMonth);
Serial.print("Month: ");
Serial.println(monthNames[monthNum - 1]);
Serial.println();
}
void setup() {
Serial.begin(115200);
initWiFi();
initNTP();
}
void loop() {
displayTimeData();
delay(1000);
}
Ensure your ESP32 connects to the correct WiFi network and has internet access to query the NTP server.