AnsweredAssumed Answered

Possible bug in RTC code

Question asked by Dominik Dráb on Mar 3, 2018
Latest reply on May 2, 2018 by Nawres GHARBI

Hi, I think there is a bug in code generated by CubeMX for RTC. Problem is that if you enable wake-up timer interrupt in Cube, it is only enabled after you first power up MCU. MX_RTC_Init checks value of backup register to prevent RTC registers being reinitialised, but also prevents HAL_RTC_Init from being called.

 

/* RTC init function */
void MX_RTC_Init(void)
{
...
  if (HAL_RTCEx_BKUPRead(&hrtc, RTC_BKP_DR0) != 0x32F2) {
...
    if (HAL_RTC_Init(&hrtc) != HAL_OK)
    {
      _Error_Handler(__FILE__, __LINE__);
    }
...
    HAL_RTCEx_BKUPWrite(&hrtc, RTC_BKP_DR0, 0x32F2);
  }
}

 

HAL_RTC_Init normally calls HAL_RTC_MspInit , which enables RTC clock and enables interrupts in NVIC. 

 

void HAL_RTC_MspInit(RTC_HandleTypeDef* rtcHandle)
{
  if(rtcHandle->Instance==RTC)
  {
...
    /* RTC clock enable */
    __HAL_RCC_RTC_ENABLE();
   
    /* RTC interrupt Init */
    HAL_NVIC_SetPriority(RTC_WKUP_IRQn, 0, 0);
    HAL_NVIC_EnableIRQ(RTC_WKUP_IRQn);
...
  }
}

 

So, if you now reset MCU, interrupt for wake-up timer will NOT be enabled (clock for RTC will stay enabled, because it is saved in BDCR register, which is preserved after reset). I think this would occur every time device is reset without  power being disconnected from Vbat.

 

Easy fix would be to still call HAL_RTC_MspInit, even if RTC registers do not need to be initialised:

 

/* RTC init function */
void MX_RTC_Init(void)
{
...
  if (HAL_RTCEx_BKUPRead(&hrtc, RTC_BKP_DR0) != 0x32F2) {
...
    if (HAL_RTC_Init(&hrtc) != HAL_OK)
    {
      _Error_Handler(__FILE__, __LINE__);
    }
...
    HAL_RTCEx_BKUPWrite(&hrtc, RTC_BKP_DR0, 0x32F2);
  }
  else
  {
    HAL_RTC_MspInit(&hrtc);
  }
}

 

Of course we can enable interrupts at different place, but it probably would be better solution if this worked correctly.

Thanks

Outcomes