#include <WiFi.h>
#include <ESP32Time.h>
#include <Wire.h>
#include "RTClib.h"
RTC_DS1307 rtc;
int i = 0;
ESP32Time Irtc(3600);
const char* ssid = "Wokwi-GUEST";
const char* password = "";
void setup() {
Serial.begin(115200);
if (!rtc.begin()) {
Serial.println("Couldn't find RTC");
Serial.flush();
while (1) delay(10);
}
WiFi.begin(ssid, password);
while(WiFi.status() != WL_CONNECTED) {
delay (1000);
i +=1;
if (i > 9){
Serial.println("Sono passati 10 secondi senza connessione WIFI - Recupero Orario da DS1307");
//rtc.adjust(DateTime(2024, 9, 20, 13, 20, 0)); //DateTime(Irtc.getEpoch())+utcOffsetInSeconds
SetTimeFromDS1307();
break;
}
}
if (WiFi.status() == WL_CONNECTED) {
Serial.println("Connessione Internet OK. Recupero Orario da server NTP ed aggiorno DS1307 e timer ESP32");
NTPUpdate();
}
//Irtc.setTime(30, 24, 15, 17, 1, 2021); // 17th Jan 2021 15:24:30
}
void loop() {
if (Serial.available()) {
char myFirstCharacter = Serial.read();
if (myFirstCharacter == 'U'){
Serial.println("Update");
NTPUpdate();
}
}
Serial.print("Internal : ");
Serial.print(Irtc.getTime()); // (String) 15:24:38
Serial.print(" ");
Serial.println(Irtc.getDate()); // (String) Sun, Jan 17 2021
Serial.print("DS1307 : ");
DateTime now = rtc.now();
Serial.print(now.hour(), DEC);
Serial.print(':');
Serial.print(now.minute(), DEC);
Serial.print(':');
Serial.print(now.second(), DEC);
Serial.print(' ');
Serial.print(now.year(), DEC);
Serial.print('/');
Serial.print(now.month(), DEC);
Serial.print('/');
Serial.print(now.day(), DEC);
Serial.println();
delay(1000);
}
void NTPUpdate() {
configTime(0, 0, "ntp1.inrim.it");
struct tm timeinfo;
if (getLocalTime(&timeinfo)){
setenv("TZ","CET-1CEST,M3.5.0/2,M10.5.0/3",1); // Now adjust the TZ. Clock settings are adjusted to show the new local time
tzset();
Irtc.setTimeStruct(timeinfo);
Serial.println("Success!");
}
delay(3000);
rtc.adjust(Irtc.getEpoch());
//rtc.adjust(DateTime(Irtc.getYear(), Irtc.getMonth()+1, Irtc.getDay(), Irtc.getHour(), Irtc.getMinute(), Irtc.getSecond())); //DateTime(Irtc.getEpoch())+utcOffsetInSeconds
}
void SetTimeFromDS1307() {
DateTime now = rtc.now();
setenv("TZ","CET-1CEST,M3.5.0/2,M10.5.0/3",1); // Now adjust the TZ. Clock settings are adjusted to show the new local time
tzset();
Irtc.setTime(now.second(),now.minute(),now.hour(),now.day(),now.month(),now.year());
}