/*
https://randomnerdtutorials.com/esp32-date-time-ntp-client-server-arduino/
https://randomnerdtutorials.com/esp32-ntp-timezones-daylight-saving/
https://github.com/josemariamendezruiz/ESP32-C3-SuperMini/blob/main/25%20ESP32%20c3%20SuperMini%20conectar%20LCD%201602%20por%20I2C
*/
#include <time.h>
#include <WiFi.h>
#include <LCD_I2C.h>
#define NTP_SERVER "hora.roa.es"
#define TIME_ZONE "CET-1CEST,M3.5.0,M10.5.0/3"
#define UTC_OFFSET 0
#define UTC_OFFSET_DST 0
LCD_I2C lcd(0x27, 16, 2);
struct tm timeInfo;
char* diaSemana[] = { "Domingo" ,"Lunes", "Martes", "Mi\351rcoles",
"Jueves", "Viernes", "S\341bado" };
char* mes[] = { "ENE" ,"FEB", "MAR", "ABR", "MAY",
"JUN", "JUL", "AGO", "SEP", "OCT", "NOV", "DIC" };
void setup() {
// prepare LCD
lcd.begin();
lcd.backlight();
getSynched();
}
void loop() {
getLocalTime(&timeInfo);
// refresh LCD once a minute
if( timeInfo.tm_sec == 0 ) {
displayLCD();
// get synched at 04:00 a.m.
if(timeInfo.tm_hour == 4 && timeInfo.tm_min == 0 ) {
getSynched();
}
delay(1000);
}
}
void getSynched() {
// reassuring message
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("Conectando a la");
lcd.setCursor(0, 1);
lcd.print("WiFi");
// connect to WiFi
WiFi.persistent(false);
WiFi.mode(WIFI_STA);
WiFi.begin("Wokwi-GUEST", "");
while (WiFi.status() != WL_CONNECTED) {
delay(250);
}
// connet to NTP & set Time Zone
configTime(UTC_OFFSET, UTC_OFFSET_DST, NTP_SERVER);
setenv("TZ", TIME_ZONE, 1);
tzset();
// another reassuring message
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("Sincronizaci\363n");
lcd.setCursor(0, 1);
lcd.print("NTP en curso");
// wait to synchcro
while(!getLocalTime(&timeInfo));
// once the clock is set up, WiFi is no longer needed
WiFi.disconnect(true);
WiFi.mode(WIFI_OFF);
// first time for time to be displayed
lcd.clear();
getLocalTime(&timeInfo);
displayLCD();
return;
}
void displayLCD() {
lcd.setCursor(0,0);
int hora = timeInfo.tm_hour;
if(hora==0) hora = 12;
if(hora>12) hora -= 12;
if(hora<10) lcd.print(0);
lcd.print(hora);
lcd.print(":");
if(timeInfo.tm_min<10) lcd.print(0);
lcd.print(timeInfo.tm_min);
lcd.setCursor(6,0);
if( timeInfo.tm_hour==0 ) lcd.print("Medianoche");
if( timeInfo.tm_hour>=1 && timeInfo.tm_hour < 6 ) lcd.print("Madrugada ");
if( timeInfo.tm_hour>=6 && timeInfo.tm_hour < 12 ) lcd.print("Ma\361ana ");
if( timeInfo.tm_hour==12 ) lcd.print("Mediod\355a ");
if( timeInfo.tm_hour>=13 && timeInfo.tm_hour < 21 ) lcd.print("Tarde ");
if( timeInfo.tm_hour>=21 && timeInfo.tm_hour ) lcd.print("Noche ");
lcd.setCursor(0,1);
lcd.print(diaSemana[timeInfo.tm_wday]);
lcd.print(", ");
lcd.print(timeInfo.tm_mday);
lcd.print(" ");
lcd.print(mes[timeInfo.tm_mon]);
return;
}