stm32duino / STM32RTC

Arduino RTC library for STM32.
127 stars 48 forks source link

[Enhancement] Add date retention functionality for STM32F1xx based boards #41

Closed josh-gaby closed 2 years ago

josh-gaby commented 3 years ago

Adds date retention through power cycles on stm32f1xx based boards

On these chips, the date details are only stored in SRAM while running, because of this, dates are not being retained after a power off even with VBAT connected.

This is fixed by using backup registers DR2 and DR3 to store the date data each time it is updated. Doing this means that the date can then be extracted and set correctly when the RTC is next initialized.

fpistm commented 3 years ago

Hi @josh-gaby Thanks for moving this PR here.

fpistm commented 3 years ago

Hi @josh-gaby Seems this PR does not cover all possible case (mainly when date change during a sleep mode): https://github.com/bxparks/AceTime/pull/50#issuecomment-792051544

I don't think I'm a fan of this PR, because if I understand it correctly, the date is not updated while the microcontroller is powered-down. The date is only preserved, so it is good for short power-loss. If the controller is powered down for more than 24 hours (or maybe even across the 23:59 -> 24:00 transition), the date is incorrect.

I think using epoch time to restore the date is a better solution and will cover all the case.

FRASTM commented 2 years ago

Thanks to a "magic nb" in another backUp register, there is a simple way to detect if the Vbat was powered during Vdd OFF. Then the date read is considered as valid or not.

FRASTM commented 2 years ago

This proposal looks like a custom appli as long as only the date is kept (stored) on each call to rtc.setDate. Keeping the date and/or time in the backUp reg will guarantee that, on the next Reset, the RTC will start counting from this value and not from 0. It should be extended to date and time (checking the 'reset' flag of the RTC_init). This is quite simple when Read/Writing the RTC CNT counter registers exporting cube HAL functions (just like the MBED did for the stm32F1)

On the stm32F1 there is one-second interrupt (see https://github.com/stm32duino/STM32RTC/pull/57) that could help storing the new Date and/or Time in BackUp Registers. In any case the RTC and backup Registers can be powered by the Vbat and kept supplied when the main Vdd is off. If not the content is lost.

josh-gaby commented 2 years ago

Its been awhile since I've had a chance to work on this, I will try and get back on it this weekend.

drbachler commented 2 years ago

I just ran into this, would be awesome to get this fix across the line and merged.

fpistm commented 2 years ago

I close this PR as it is superseded by #58.