ARM:0016 STM32CubeMX – problems with RTC

This is a very short message about proper initialization of RTC (real time clock). There is one trick designed in HAL and in several internet resources it is wrongly described.
Proper RTC init:
Find “MX_RTC_Init(void)“, scroll to “USER CODE BEGIN Check_RTC_BKUP“. Now read one of the available user variables from “backup” RAM and open new “IF“:

/* USER CODE BEGIN Check_RTC_BKUP */
if(HAL_RTCEx_BKUPRead(&hrtc,RTC_BKP_DR1)!= 0x5051)
{
/* USER CODE END Check_RTC_BKUP */

Number “0×5051″ is random value, it can be any. Maybe only zero or max value is not good option, as it may be get from uninitialized ram.
Now scroll lots of code and add…

....
/* USER CODE BEGIN RTC_Init 2 */
    } // Kitame user code virsuje yra IF komanda. Čia ji užsidaro. (closing IF from beginning)
    else
    {
// LAIKAS BUVO ISSAUGOTAS, NES USER REGISTRAS TURI MAGIC skaiciu 0x5051 (battery backup is valid- we received "magic" number)
// Čia galima ką nors padaryti iš tos laimės arba pagalvoti apie kalendoriaus atstatymą. Sako kad jis nelabai
    }

//Čia įrašom tą MAGIC skaičių. Jis po pilno reseto ir RTC mirties turi neišlikti. (Write "magic" number to RAM)
HAL_RTCEx_BKUPWrite(&hrtc, RTC_BKP_DR1, 0x5051);//Write data to the specified backing area register
/* USER CODE END RTC_Init 2 */

All this stuff is made to force users to validate RTC status. In some internet examples there was even a recommendation to exit init code before full initialization. Meanwhile reading “magic” value ensures that the programmer checks RTC status and initializes it if it fails.

P.S. To start RTC second interrupt just execute this macro:

__HAL_RTC_SECOND_ENABLE_IT(&hrtc,RTC_IT_SEC);

About Administrator

I am owner of this site.
This entry was posted in Anything, MCU. Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>