#ifdef ESP8266
#include <ESP8266WiFi.h>
#elif defined(ESP32)
#include <WiFi.h>
#define configTime(MYTZ, ...) configTzTime(MYTZ, ##__VA_ARGS__)
#endif
#include <time.h>
// Timezone definition to get properly time from NTP server
#define MYTZ "CET-1CEST-2,M3.5.0/2,M10.5.0/3"
struct tm Time;
//////////////////////////////// NTP Time /////////////////////////////////////////
void getUpdatedtime(const uint32_t timeout)
{
uint32_t start = millis();
do
{
time_t now = time(nullptr);
Time = *localtime(&now);
} while (millis() - start < timeout && Time.tm_year <= (1970 - 1900));
}
void setup() {
// put your setup code here, to run once:
Serial.begin(115200);
WiFi.begin("Wokwi-GUEST", "", 6);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.print("\nWiFi connected. IP address: ");
Serial.println(WiFi.localIP());
// Setup timezone and NTP servers
configTime(MYTZ, "time.google.com", "time.windows.com", "pool.ntp.org");
// The first time it take some time to sync
getUpdatedtime(10000);
}
void loop() {
// put your main code here, to run repeatedly:
delay(10); // this speeds up the simulation
static uint32_t printTime;
if (millis() - printTime > 1000) {
printTime = millis();
getUpdatedtime(0);
char buffer [80];
/*
https://cplusplus.com/reference/ctime/strftime/
*/
strftime (buffer,80,"Now it's %Ec\n", &Time);
Serial.printf (buffer);
}
}