/*
https://github.com/Makuna/Rtc
Arduino Real Time Clock library.
*/
#include <Wire.h> // must be included here so that Arduino library object file references work
#include <RtcDS3231.h>
RtcDS3231<TwoWire> Rtc(Wire);
RtcDateTime dt, now;
bool rtclock_err;
void setup() {
Serial.begin(9600);
Rtc.Begin();
//RtcDateTime compiled = RtcDateTime(__DATE__, __TIME__);
//Rtc.SetDateTime(compiled + 0*60*60 + 8);
//Rtc.SetDateTime(RtcDateTime(2018, 1, 17, 7, 53, 00));
}
void loop() {
static char date[11];
static char time[9];
rtclock();
snprintf(date, 11, "%04u-%02u-%02u", now.Year(), now.Month(), now.Day());
snprintf(time, 9, "%02d:%02d:%02d", now.Hour(), now.Minute(), now.Second());
static int sec = ~now.Second();
if (sec != now.Second()) {
sec = now.Second();
Serial.print(date);
Serial.print(" ");
Serial.print(time);
if (rtclock_err) Serial.print(" rtclock ER");
else Serial.print(" rtclock OK");
Serial.println("");
}
}
void rtclock() {
static bool init = true;
static unsigned long elapse;
static float tolerance = 4.0 / 3600.0; // tolerance = 4.0 sec/hrs (Arduino R4 Wifi);
if (init) {
init = false;
dt = Rtc.GetDateTime();
elapse = millis();
rtclock_err = !Rtc.IsDateTimeValid();
}
if (rtclock_err) {
if (millis() - elapse > 1000) init = true;
} else if (millis() - elapse > 21600000) init = true; //read rtclock every 21600000ms (= 6 hrs)
now = dt + round((millis() - elapse) * (1.0 + tolerance) / 1000.0);
}