// Learn about the ESP32 WiFi simulation in
// https://docs.wokwi.com/guides/esp32-wifi
// Derived from Wokwi "ESP32 NTP Clock"
// https://wokwi.com/projects/321525495180034642
// Read https://randomnerdtutorials.com/esp32-ntp-timezones-daylight-saving/
// for more information on using timezones
#include <WiFi.h>
#include <Wire.h>
#include <LiquidCrystal_I2C.h>
LiquidCrystal_I2C LCD = LiquidCrystal_I2C(0x27, 16, 2);
#define NTP_SERVER "pool.ntp.org"
#define UTC_OFFSET 0
#define UTC_OFFSET_DST 0
void spinner() {
static int8_t counter = 0;
const char* glyphs = "\xa1\xa5\xdb";
LCD.setCursor(15, 1);
LCD.print(glyphs[counter++]);
if (counter == strlen(glyphs)) {
counter = 0;
}
}
void printLocalTime() {
struct tm timeinfo;
if (!getLocalTime(&timeinfo)) {
LCD.setCursor(0, 1);
LCD.println("Connection Err");
return;
}
LCD.setCursor(8, 0);
LCD.println(&timeinfo, "%H:%M:%S");
LCD.setCursor(0, 1);
LCD.println(&timeinfo, "%Y-%m-%d %Z");
}
void setup() {
Serial.begin(115200);
LCD.init();
LCD.backlight();
LCD.setCursor(0, 0);
LCD.print("Connecting to ");
LCD.setCursor(0, 1);
LCD.print("WiFi ");
WiFi.begin("Wokwi-GUEST", "", 6);
while (WiFi.status() != WL_CONNECTED) {
delay(250);
spinner();
}
Serial.println("");
Serial.println("WiFi connected");
Serial.print("IP address: ");
Serial.println(WiFi.localIP());
LCD.clear();
LCD.setCursor(0, 0);
LCD.println("Online");
LCD.setCursor(0, 1);
LCD.println("Updating time...");
configTime(UTC_OFFSET, UTC_OFFSET_DST, NTP_SERVER);
setTimezone("CET-1CEST,M3.5.0,M10.5.0/3");
// initTime("CET-1CEST,M3.5.0,M10.5.0/3"); // TZ-String for Europe/Berlin
}
void loop() {
int i;
for (i=0; i<30; i++) {
printLocalTime();
delay(1000);
}
Serial.println();
Serial.println("Now change the time. 10 seconds before DST takes effect. (last Sunday of Oct)");
setTime(2023,10,29,1,59,50,0); // Set it to 10 seconds before daylight savings comes in.
for(i=0; i<20; i++){
delay(1000);
printLocalTime();
}
Serial.println();
Serial.println("Now change the time. 10 seconds before DST ends. (last Sunday of Mar)");
setTime(2024,3,31,2,59,50,1); // Set it to 10 seconds before daylight savings comes in.
for(i=0; i<20; i++){
delay(1000);
printLocalTime();
}
}
void setTimezone(String timezone){
Serial.printf(" Setting Timezone to %s\n",timezone.c_str());
setenv("TZ",timezone.c_str(),1); // Now adjust the TZ. Clock settings are adjusted to show the new local time
tzset();
}
void setTime(int yr, int month, int mday, int hr, int minute, int sec, int isDst){
struct tm tm;
tm.tm_year = yr - 1900; // Set date
tm.tm_mon = month-1;
tm.tm_mday = mday;
tm.tm_hour = hr; // Set time
tm.tm_min = minute;
tm.tm_sec = sec;
tm.tm_isdst = isDst; // 1 or 0
time_t t = mktime(&tm);
Serial.printf("Setting time: %s", asctime(&tm));
struct timeval now = { .tv_sec = t };
settimeofday(&now, NULL);
}