Dear Arduino-Community,
I'm trying to understand the inner workings of the Timelib library:
and stumbled upon the following Code snippet:
time_t now() {
// calculate number of seconds passed since last call to now()
while (millis() - prevMillis >= 1000) {
// millis() and prevMillis are both unsigned ints thus the subtraction will always be the absolute value of the difference
sysTime++;
prevMillis += 1000;
#ifdef TIME_DRIFT_INFO
sysUnsyncedTime++; // this can be compared to the synced time to measure long term drift
#endif
}
if (nextSyncTime <= sysTime) {
if (getTimePtr != 0) {
time_t t = getTimePtr();
if (t != 0) {
setTime(t);
} else {
nextSyncTime = sysTime + syncInterval;
Status = (Status == timeNotSet) ? timeNotSet : timeNeedsSync;
}
}
}
return (time_t)sysTime;
}
I have a hard time understanding how the while loop works here. Usually, when I see a while loop, I immediately think of blocking issues, but surely he found a clever solution for not making that happen, I just don't understand yet.
getTimePtr != 0
Is basically there to check, if there is any function for getting the time (NTP, RTC) I guess?
if (t != 0) {
setTime(t);
} else {
nextSyncTime = sysTime + syncInterval;
Status = (Status == timeNotSet) ? timeNotSet : timeNeedsSync;
}
Is this expression there to check, if a sync was successfull and when do we actually get into the else block?
(t != 0)
Thanks for any help!
Kind regards