rtctimestampbias/rtctimestampbias.ino

52 lines
1.8 KiB
C++

// RTC timestamp bias: Arduino with DS1307RTC example
// https://gitlab.com/simplemicrocontrollers/rtctimestampbias
#include <Thread.h>
#include <DS1307RTC.h>
// Time bias correction variables:
int correctionBias = 0; // Daily clock correction in seconds
byte correctionHour = 3; // 3AM - daily correction time
long correctionCheck = 300000;
bool correctionReady = true;
Thread correctionThread = Thread(); // Time bias correction thread
void setup() {
Serial.begin(9600); // Initializes the Serial connection @ 9600 baud for debug
while (!Serial); // Wait until Arduino Serial Monitor opens
setSyncProvider(RTC.get); // The function to get the time from the RTC
if(timeStatus()!= timeSet) { // Checking the time setting
Serial.println("Unable to sync with the RTC");
} else {
// Serial.println("RTC has set the system time");
Serial.println(now()); // Sending a timestamp to the serial port if a RTC is detected
}
// Time bias correction thread initialization:
correctionThread.onRun(correctionLoop);
correctionThread.setInterval(correctionCheck);
}
void loop() {
// Threads:
if (correctionThread.shouldRun())
correctionThread.run();
}
void correctionLoop() {
if (hour() == correctionHour) {
if (correctionReady) {
tmElements_t RTCtime;
RTC.read(RTCtime);
time_t RTCtimestamp;
RTCtimestamp = makeTime(RTCtime);
tmElements_t timeNew;
time_t newTimestamp = RTCtimestamp - correctionBias; // minus correctionBias seconds everyday
// if ((day() % 5) == 0) newTimestamp = newTimestamp - 1; // minus 1 sec every 5 days (-0.2sec everyday)
breakTime(newTimestamp, timeNew);
RTC.write(timeNew);
setSyncProvider(RTC.get);
correctionReady = false;
}
} else correctionReady = true;
}