简体   繁体   中英

Getting current time from STM32 RTC after period of time

I wonder that whether it is possible to reach current time from RTC after period of time which Vdd is not present, Vbat is present. Here is simple example;

  1. Vdd is present -> time: 19:49:53
  2. Vdd is not present but Vbat is present for 1 minute
  3. Vdd is present -> time: ?t item

If I am not wrong it begins from the time I have set beginning of the code. But, I want to reach current time. Is there a way to do this?

This is the whole point and normal use of the RTC peripheral. It carries on counting as long as the Vbat supply is present. It wouldn't be a very good clock if it didn't!

Here is my solution to problem:

void MX_RTC_Init(void)
{
   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 = 7811;
   hrtc.Init.OutPut = RTC_OUTPUT_DISABLE;
   hrtc.Init.OutPutPolarity = RTC_OUTPUT_POLARITY_HIGH;
   hrtc.Init.OutPutType = RTC_OUTPUT_TYPE_OPENDRAIN;
   if (HAL_RTC_Init(&hrtc) != HAL_OK)
   {
     Error_Handler();
   }

   /* USER CODE BEGIN Check_RTC_BKUP */
   if (HAL_RTCEx_BKUPRead(&hrtc, RTC_BKP_DR1) != 0xBEBE)
   {
   // Write Back Up Register 1 Data
   HAL_PWR_EnableBkUpAccess();
   // Writes a data in a RTC Backup data Register 1
   HAL_RTCEx_BKUPWrite(&hrtc, RTC_BKP_DR1, 0xBEBE);
   HAL_PWR_DisableBkUpAccess();

   //Turn LED2
   HAL_GPIO_WritePin(GPIOB, GPIO_PIN_2, GPIO_PIN_SET);
         HAL_Delay(2000);
         HAL_GPIO_WritePin(GPIOB, GPIO_PIN_2, GPIO_PIN_RESET);

}
 else
 {
   // data register already written so turn LED3
   return;

 }
 /* USER CODE END Check_RTC_BKUP */

 /** Initialize RTC and set the Time and Date
 */
 sTime.Hours = 19;
 sTime.Minutes = 55;
 sTime.Seconds = 0;
 sTime.DayLightSaving = RTC_DAYLIGHTSAVING_NONE;
 sTime.StoreOperation = RTC_STOREOPERATION_RESET;
 if (HAL_RTC_SetTime(&hrtc, &sTime, RTC_FORMAT_BIN) != HAL_OK)
 {
  Error_Handler();
 }
 sDate.WeekDay = RTC_WEEKDAY_MONDAY;
 sDate.Month = RTC_MONTH_MARCH;
 sDate.Date = 21;
 sDate.Year = 0;

 if (HAL_RTC_SetDate(&hrtc, &sDate, RTC_FORMAT_BIN) != HAL_OK)
 {
  Error_Handler();
 }
 /* USER CODE BEGIN RTC_Init 2 */

 /* USER CODE END RTC_Init 2 */

}

if it is the first time I run the code. RTC is intialized and take values. But if it is afterwards controller reset or Vdd is not present, controller initiliaze RTC but since Backup register has been already written, RTC init function continues where it left.

(See /* USER CODE END Check_RTC_BKUP */ part)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM