2017-10-25 03:09 AM
Hi there,
I'm using the RTC on my STM32F103 to keep the date and time but when I reset the MCU the date is lost.
I know that this behaviour is due to the RTC implementation ( it uses a counter ).
To prevent the date loss, I think to store the date into one or more backup register.
My date is composed by 3 byte (Year, Month and Date).
Could any one provide me a example about how to solve my problem?
Thanks!
#rtc-time-and-date #backup-registers #rtc-backup Note: this post was migrated and contained many threaded conversations, some content may be missing.2017-10-26 04:58 AM
{CODE()}
void save_value(uint32_t save)
{ HAL_RTCEx_BKUPWrite(&hrtc, RTC_BKP_DR0, save);}uint32_t get_value(void)
{ return HAL_RTCEx_BKUPRead(&hrtc, RTC_BKP_DR0);}{CODE}
2017-10-26 02:17 PM
Please take a look at this comment. This will help you fix the code:
2017-10-27 01:12 AM
I do the same things but into two custom functions in order to store and load the date from BKP register (DR2 and DR3). Using custom function allow you to store the date in any moment without wait a new day.
Unfortunately this method works only when the power loss is less then a day, otherwise, after two or more days, the date will be wrong.
I think that the best way is to store the unix time into the RTC 32bit counter since the RTC counter has a backup battery.
2017-10-27 01:35 AM
hello!
Have a look also to
https://community.st.com/0D50X00009XkekSSAR
regards
vf
2017-10-27 01:54 AM
No, it does work even after power loss for a day or more. Take a look at HAL_RTC_GetTime, it
explicitly calculates days elapsed since power loss and then passes that to RTC_DateUpdate(hrtc, days_elapsed); which will update the date based on days elapsed.
Seems they have implemented this functionality, but they have forgotten to implement date save/restore.
2017-10-27 02:50 AM
Thanks for the explanation. I don't look inside RTC_DateUpdate.
I solved in this way:
static void RTC_StoreDateIntoBkpReg( RTC_DateTypeDef* dateRtc )
{ uint32_t dateToStore;memcpy( &dateToStore, dateRtc, sizeof(dateToStore) );
HAL_RTCEx_BKUPWrite( &hrtc, RTC_BKP_DR2, (dateToStore >> 16) ); HAL_RTCEx_BKUPWrite( &hrtc, RTC_BKP_DR3, (dateToStore & 0xFFFF) );}static void RTC_LoadDateFromBkpReg( RTC_DateTypeDef* dateRtc )
{ uint32_t dateToStore; dateToStore = HAL_RTCEx_BKUPRead( &hrtc, RTC_BKP_DR3 ); dateToStore |= ( HAL_RTCEx_BKUPRead( &hrtc, RTC_BKP_DR2 ) << 16 ); memcpy( dateRtc, &dateToStore, sizeof(dateToStore) );}void RTC_Initialize( void )
{ RTC_DateTypeDef dateRtc; /* Restore the date form backup registers */ RTC_LoadDateFromBkpReg( &dateRtc ); RTC_SetDate( &dateRtc, RTC_FORMAT_BCD ); /* Get the date in order to allow HAL to check if a day is elapsed and update the date if it is necessaty */ RTC_GetDate( &dateRtc, RTC_FORMAT_BCD ); }I tested now this implementation setting the time ad 23:59:00 and when power up the board the date in correct 2017/10/28.
Thanks to everybody for the help!