Mohammad A

STM32F103 RTC + VBAT restore date after power loss

Discussion created by Mohammad A on Oct 24, 2017
Latest reply on Feb 12, 2018 by etha.bhargav

As you may probably have noticed, 103 series are using RTC V1 which is not capable of keeping track of date in battery mode (It actually does support in hardware, but for some reasons, they did not implement it in HAL).


To fix this issue there are two approaches.

Fixing available functions in HAL (the easy one, the best one),

and the next is using RTC second counters registers and <time.h> (the hard one, not as good as previous)


I will describe the easy one.

Open stm32f1xx_hal_rtc.c and find function static void RTC_DateUpdate(RTC_HandleTypeDef* hrtc, uint32_t DayElapsed).

Append these lines at the end of the function:

  uint32_t dateToStore;


  HAL_RTCEx_BKUPWrite(&hrtc, RTC_BKP_DR2,dateToStore);

This will store every changes made to current date into the backup SRAM.


Open rtc.c and add these lines at the end of function void MX_RTC_Init(void):

       uint32_t dateMem = HAL_RTCEx_BKUPRead(&hrtc, RTC_BKP_DR2);


       if (HAL_RTC_SetDate(&hrtc, &DateToUpdate, RTC_FORMAT_BCD) != HAL_OK)
         _Error_Handler(__FILE__, __LINE__);

       HAL_RTC_GetTime(&hrtc, &sTime, RTC_FORMAT_BIN);


This part will restore date from RTC_BPK_DR2.


I don't know if this method is implemented in any example available at firmware directories, but this will quickly fix the lack of this feature.


Note that this will calculate and restore the correct date even after passing days.