问题:
STM32F1中RTC 不像 F4中,是一个单独模块。其就是一个计数器,查看HAL库中时间和日期的设置发现,在日期设置的时候,HAL库并没有将日期换算为计数器的值。
库源码如下
日期设置:
HAL_StatusTypeDef HAL_RTC_SetTime(RTC_HandleTypeDef *hrtc, RTC_TimeTypeDef *sTime, uint32_t Format)
{
uint32_t counter_time = 0U, counter_alarm = 0U;
/* Check input parameters */
if((hrtc == NULL) || (sTime == NULL))
{
return HAL_ERROR;
}
/* Check the parameters */
assert_param(IS_RTC_FORMAT(Format));
/* Process Locked */
__HAL_LOCK(hrtc);
hrtc->State = HAL_RTC_STATE_BUSY;
if(Format == RTC_FORMAT_BIN)
{
assert_param(IS_RTC_HOUR24(sTime->Hours));
assert_param(IS_RTC_MINUTES(sTime->Minutes));
assert_param(IS_RTC_SECONDS(sTime->Seconds));
counter_time = (uint32_t)(((uint32_t)sTime->Hours * 3600U) + \ //HAL库这里计算的时间,后面写入计数器的
((uint32_t)sTime->Minutes * 60U) + \ //也就是这个值
((uint32_t)sTime->Seconds));
}
else
{
assert_param(IS_RTC_HOUR24(RTC_Bcd2ToByte(sTime->Hours)));
assert_param(IS_RTC_MINUTES(RTC_Bcd2ToByte(sTime->Minutes)));
assert_param(IS_RTC_SECONDS(RTC_Bcd2ToByte(sTime->Seconds)));
counter_time = (((uint32_t)(RTC_Bcd2ToByte(sTime->Hours)) * 3600U) + \
((uint32_t)(RTC_Bcd2ToByte(sTime->Minutes)) * 60U) + \
((uint32_t)(RTC_Bcd2ToByte(sTime->Seconds))));
}
/* Write time counter in RTC registers */
if (RTC_WriteTimeCounter(hrtc, counter_time) != HAL_OK) //更新计数器,并没设计到日期
{
/* Set RTC state */
hrtc->State = HAL_RTC_STATE_ERROR;
/* Process Unlocked */
__HAL_UNLOCK(hrtc);
return HAL_ERROR;
}
else
{
/* Clear Second and overflow flags */
CLEAR_BIT(hrtc->Instance->CRL, (RTC_FLAG_SEC | RTC_FLAG_OW));
/* Read current Alarm counter in RTC registers */
counter_alarm = RTC_ReadAlarmCounter(hrtc);
/* Set again alarm to match with new time if enabled */
if (counter_alarm != RTC_ALARM_RESETVALUE)
{
if(counter_alarm < counter_time)
{
/* Add 1 day to alarm counter*/
counter_alarm += (uint32_t)(24U * 3600U);
/* Write new Alarm counter in RTC registers */
if (RTC_WriteAlarmCounter(hrtc, counter_alarm) != HAL_OK)
{
/* Set RTC state */
hrtc->State = HAL_RTC_STATE_ERROR;
/* Process Unlocked */
__HAL_UNLOCK(hrtc);
return HAL_ERROR;
}
}
}
hrtc->State = HAL_RTC_STATE_READY;
__HAL_UNLOCK(hrtc);
return HAL_OK;
}
}
HAL日期设置:
HAL_StatusTypeDef HAL_RTC_GetTime(RTC_HandleTypeDef *hrtc, RTC_TimeTypeDef *sTime, uint32_t Format)
{
uint32_t counter_time = 0U, counter_alarm = 0U, days_elapsed = 0U, hours = 0U;
/* Check input parameters */
if((hrtc == NULL) || (sTime == NULL))
{
return HAL_ERROR;
}