STM32L412 issues with RTC
Hello! I am using the RTC of a STM32L412 with 32kHz LSI to wake the MCU from STOP2 mode after a specified time in seconds. Now I´m having two issues:
1) I cannot program the MCU using a ST-Link V2 with current Firmware, when the STOP2 mode is active. ("Error in initializing ST-LINK device. Reason: No device found on target."). I already "lost" one device, now I´m doing a 10s HAL_Delay() in the beginning before the program starts to quickly flash new firmware on-board. Is there a workaround on this? How can I rescue my device that goes directly into STOP2 mode to flash it again?
2) Accuracy: I have tried a 20 seconds sleep in the STOP2 low-power mode. The program prints out the RTC time, and it seems that it is sleeping for slightly less than 20 seconds. Which is a weird behaviour. If time would be higher I could think of the printf() execution time etc. I calculated the wakeup-timer like this:
wakeUpCounter = wakeUpTime / (LSI_Prescaler / LSE_Frequency) = 20s / (16 / 32000Hz) = 40000
Here´s my code:
uint16_t secondsToSleep = 20;
for (uint16_t ctr=0;ctr<500;ctr++) {
printf("Current RTC time >>> %lu\r\n", (unsigned long)getEpochTimeFromRTC(hrtc));
HAL_SuspendTick();
HAL_RTCEx_SetWakeUpTimer_IT(&hrtc, (secondsToSleep * 2000), RTC_WAKEUPCLOCK_RTCCLK_DIV16,0); // Set wake-up timer
HAL_PWREx_EnterSTOP2Mode(PWR_STOPENTRY_WFI); // Enter STOP 2 mode
HAL_RTCEx_DeactivateWakeUpTimer(&hrtc); // Code continues after waking up from STOP2 low-power mode
SystemClock_Config();
HAL_ResumeTick();
}
The RTC init looks like this:
static void MX_RTC_Init(void)
{
/* USER CODE BEGIN RTC_Init 0 */
/* USER CODE END RTC_Init 0 */
RTC_TimeTypeDef sTime = {0};
RTC_DateTypeDef sDate = {0};
/* USER CODE BEGIN RTC_Init 1 */
/* USER CODE END RTC_Init 1 */
/** Initialize RTC Only
*/
hrtc.Instance = RTC;
hrtc.Init.HourFormat = RTC_HOURFORMAT_24;
hrtc.Init.AsynchPrediv = 127;
hrtc.Init.SynchPrediv = 255;
hrtc.Init.OutPut = RTC_OUTPUT_DISABLE;
hrtc.Init.OutPutRemap = RTC_OUTPUT_REMAP_NONE;
hrtc.Init.OutPutPolarity = RTC_OUTPUT_POLARITY_HIGH;
hrtc.Init.OutPutType = RTC_OUTPUT_TYPE_OPENDRAIN;
hrtc.Init.OutPutPullUp = RTC_OUTPUT_PULLUP_NONE;
if (HAL_RTC_Init(&hrtc) != HAL_OK)
{
Error_Handler();
}
/* USER CODE BEGIN Check_RTC_BKUP */
/* USER CODE END Check_RTC_BKUP */
/** Initialize RTC and set the Time and Date
*/
sTime.Hours = 0x0;
sTime.Minutes = 0x0;
sTime.Seconds = 0x0;
sTime.DayLightSaving = RTC_DAYLIGHTSAVING_NONE;
sTime.StoreOperation = RTC_STOREOPERATION_RESET;
if (HAL_RTC_SetTime(&hrtc, &sTime, RTC_FORMAT_BCD) != HAL_OK)
{
Error_Handler();
}
sDate.WeekDay = RTC_WEEKDAY_MONDAY;
sDate.Month = RTC_MONTH_JANUARY;
sDate.Date = 0x1;
sDate.Year = 0x0;
if (HAL_RTC_SetDate(&hrtc, &sDate, RTC_FORMAT_BCD) != HAL_OK)
{
Error_Handler();
}
/** Enable the WakeUp
*/
if (HAL_RTCEx_SetWakeUpTimer_IT(&hrtc, 0, RTC_WAKEUPCLOCK_RTCCLK_DIV16, 0) != HAL_OK)
{
Error_Handler();
}
/* USER CODE BEGIN RTC_Init 2 */
/* USER CODE END RTC_Init 2 */
}
