arduino-libraries / RTCZero

RTC Library for SAMD21 based boards
http://arduino.cc/en/Reference/RTC
GNU Lesser General Public License v2.1
76 stars 79 forks source link

Time jumps ahead during sleep. #29

Open sathibault opened 7 years ago

sathibault commented 7 years ago

I'm observing a jump in the time returned by getEpoch on the Feather M0. During setup I'm calling rtc.begin() and shortly after getEpoch returns 943920000 (30 Nov 1999 00:00:00). I set the alarm for 1 min later and it wakes up correctly, but getEpoch now returns 946684861 (01 Jan 2000 00:01:01). Anyone have thoughts on what's causing this?

GabrielNotman commented 7 years ago

I believe there may be some initialisation issue as the RTC range starts 01 Jan 2000 00:00:00. The initial value you are reading is invalid. I believe the RTC may currently require a single clock cycle (1 second) to initialise the values correctly.

You should only see this jump once, after initialisation and it is unrelated to entering sleep mode.

I'll try and investigate to see if the setup can be modified to ensure the clock value is always valid.

agdl commented 7 years ago

@sathibault can you please paste here your sketch?

sathibault commented 7 years ago

It's part the RxFusion library (https://github.com/sathibault/RxFusion) that provides automatic sleep management. I've worked around this issue calling getEpoch every time it wakes: https://github.com/sathibault/RxFusion/blob/master/include/arduino/samd-sleep.h#L95

GabrielNotman commented 7 years ago

I can confirm that this issue exists. It will present, in the first second, after the RTC is reset (after a POR reset, or by passing true to the rtc.begin() call).

I have an example demonstrating this here: https://github.com/GabrielNotman/AutonomoTesting/blob/master/RTC/Test_RTC_Skip/Test_RTC_Skip.ino

This was not tested on a Feather M0, but another SAMD21 based board. Similarly, I found that I was able to recreate the issue without doing anything in sleep mode.

The issue is that the CLOCK register is zeroed after certain resets, or deliberately during initialisation. This causes issues with the MONTH and DAY values as the getEpoch() conversion requires that these values are at least one.

After one second elapses, the CLOCK register is updated after which both MONTH and DAY have valid values. However, before that first update, the reported epoch time will be Jan 1st 2000, 00:00:00, minus one month and one day (so Nov 30th 1999, 00:00:00).

I believe the best fix for this is to test the month/day values at the end of the RTC initialisation, and if these are invalid then set the clock to a default time/date. This would need to be done even if attempting to preserve the existing time as certain resets will create an invalid time.

I'll submit a fix for the library, when I get chance.

sathibault commented 7 years ago

Cool, thanks for digging into it!

GabrielNotman commented 7 years ago

I've added a fix for this in PR #30.