NTPServer is an Arduino library for ESP devices that implements a simple asynchronous NTP server. This library listens for incoming NTP requests on UDP port 123 and responds with the current time (based on the ESP's local time). It is ideal for projects that require time synchronization or need to serve time information to other devices on the network.
- Asynchronous Operation: Uses [AsyncUDP] for non-blocking UDP communications.
- Customizable Identifier: Easily configure the server's identifier (default is "NTP") used in the NTP response.
- Lightweight and Easy-to-Use: Designed for simplicity and efficiency on ESP32 and similar devices.
- Flexible: Works with any system where the ESP's local time is correctly set (e.g., after a call to
configTime()
).
- Hardware: ESP32 or compatible boards.
- Libraries:
- [AsyncUDP]
- Arduino core for ESP32
-
Download or Clone:
Download or clone this repository. -
Copy to Libraries:
Copy theNTPServer
folder into your Arduino libraries directory (typically found inDocuments/Arduino/libraries
). -
Restart Arduino IDE:
If the Arduino IDE is already running, restart it to recognize the new library.
-
Add to Project:
Place theNTPServer
folder into thelib/
directory of your PlatformIO project. -
Build:
PlatformIO will automatically detect and build the library as part of your project.
Below is a simple example sketch demonstrating how to use the NTPServer library:
#include <WiFi.h>
#include "NTPServer.h"
// Replace with your WiFi credentials
const char* ssid = "your_ssid";
const char* password = "your_password";
// Create an instance of the NTPServer
NTPServer ntpServer;
void setup() {
Serial.begin(115200);
delay(1000);
// Connect to WiFi
Serial.println("Connecting to WiFi...");
WiFi.begin(ssid, password);
unsigned long startAttemptTime = millis();
// Wait for the connection with a timeout of 15 seconds
while (WiFi.status() != WL_CONNECTED) {
if (millis() - startAttemptTime > 15000) {
Serial.println("\nWiFi connection timeout. Restarting...");
ESP.restart();
}
delay(500);
Serial.print(".");
}
Serial.println("\nWiFi connected!");
Serial.print("IP address: ");
Serial.println(WiFi.localIP());
// Optionally, synchronize time using an external NTP server.
// Uncomment the following block if needed:
/*
configTime(0, 0, "pool.ntp.org", "time.nist.gov", "time.google.com");
Serial.print("Waiting for time synchronization");
while (time(nullptr) < 100000) {
delay(500);
Serial.print(".");
}
Serial.println("\nTime synchronized!");
*/
// Optionally, set a custom identifier (default is "NTP")
// ntpServer.setIdentifier("ESP");
// Start the NTP server on the default port (123)
if (!ntpServer.begin(123)) {
Serial.println("Failed to start the NTP server!");
}
}
void loop() {
// The server runs asynchronously. No action required here.
}