57 lines
1.3 KiB
C++
57 lines
1.3 KiB
C++
#include "esp_system.h"
|
|
#include "sntp.h"
|
|
#include "time.h"
|
|
#include <WiFi.h>
|
|
#include <WiFiUdp.h>
|
|
|
|
const char* ssid = "Wokwi-GUEST";
|
|
const char* password = "";
|
|
|
|
const char* ntpServer1 = "pool.ntp.org";
|
|
const char* ntpServer2 = "time.nist.gov";
|
|
const long gmtOffset_sec = 2 * 3600; // GMT + 2
|
|
const int daylightOffset_sec = 0;
|
|
|
|
void printLocalTime()
|
|
{
|
|
struct tm timeinfo;
|
|
if (!getLocalTime(&timeinfo)){
|
|
Serial.println("No time available (yet)");
|
|
return;
|
|
}
|
|
Serial.println(&timeinfo, "%A, %B %d %Y %H:%M:%S");
|
|
}
|
|
|
|
// Callback function (get's called when time adjusts via NTP)
|
|
void timeavailable(struct timeval *t)
|
|
{
|
|
Serial.println("Got time adjustment from NTP!");
|
|
printLocalTime();
|
|
}
|
|
|
|
void setup()
|
|
{
|
|
Serial.begin(115200);
|
|
|
|
// set notification call-back function
|
|
sntp_set_time_sync_notification_cb(timeavailable);
|
|
|
|
// This will set configured NTP servers and the new GMT and daylight offsets for IST.
|
|
configTime(gmtOffset_sec, daylightOffset_sec, ntpServer1, ntpServer2);
|
|
|
|
// Connect to WiFi
|
|
Serial.printf("Connecting to %s ", ssid);
|
|
WiFi.begin(ssid, password);
|
|
while (WiFi.status() != WL_CONNECTED) {
|
|
delay(500);
|
|
Serial.print(".");
|
|
}
|
|
Serial.println(" CONNECTED");
|
|
}
|
|
|
|
void loop()
|
|
{
|
|
delay(5000);
|
|
printLocalTime(); // it will take some time to sync time :)
|
|
}
|