Created
June 18, 2023 23:09
-
-
Save lonelybinary/4573a73a47ecca85f94452290ca2387c to your computer and use it in GitHub Desktop.
Arduino ESP32-S3 Sync Internal RTC with NTP Server
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <WiFi.h> | |
#include "time.h" | |
const char *ssid = "YOUR_WIFI_SSID"; | |
const char *password = "YOUR_WIFI_PASSWORD"; | |
const char *ntpServer = "ntp.lonelybinary.com"; | |
const long gmtOffset_sec = 3600L * 10; | |
const int daylightOffset_sec = 0; | |
void setup() | |
{ | |
Serial.begin(115200); | |
Serial.print ("Connecting to WiFi network "); | |
WiFi.begin(ssid, password); | |
while (WiFi.status() != WL_CONNECTED) | |
{ | |
delay(500); | |
Serial.print("."); | |
} | |
Serial.println(""); | |
/* | |
Sync time with NTP server and update ESP32 RTC | |
getLocalTime() return false if time is not set | |
*/ | |
Serial.print("Syncing time with NTP server "); | |
struct tm timeinfo; | |
while (!getLocalTime(&timeinfo)) | |
{ | |
configTime(gmtOffset_sec, daylightOffset_sec, ntpServer); | |
delay(500); | |
Serial.print(""); | |
} | |
Serial.println(""); | |
// disconnect WiFi | |
WiFi.disconnect(true); | |
WiFi.mode(WIFI_OFF); | |
} | |
void loop() | |
{ | |
struct tm timeinfo; | |
getLocalTime(&timeinfo); | |
Serial.println(&timeinfo, "%A, %B %d %Y %H:%M:%S"); | |
delay(10000); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment