获取时间点
uint32_t RTC_TimeGet(uint8_t *h,uint8_t *m,uint8_t *s,uint32_t *ss)
{
uint32_t RTC_Time=0;
uint32_t RTC_SubSeconds=0;
uint8_t time[7];
RTC_TimeTypeDef stimestructureget={0}; //Attention! Initial the value
RTC_DateTypeDef sdatestructureget={0}; //Attention! Initial the value
stimestructureget.DayLightSaving=RTC_DAYLIGHTSAVING_NONE;
stimestructureget.StoreOperation=RTC_STOREOPERATION_RESET;
sdatestructureget.WeekDay=RTC_WEEKDAY_MONDAY;
HAL_RTC_GetTime(&RtcHandle, &stimestructureget, RTC_FORMAT_BIN);
HAL_RTC_GetDate(&RtcHandle, &sdatestructureget, RTC_FORMAT_BIN);
RTC_SubSeconds=((uint32_t)(stimestructureget.SecondFraction-stimestructureget.SubSeconds)) * ((uint32_t)(1000/RTC_SPRE_CLK)) / ((uint32_t)(stimestructureget.SecondFraction+1)) ; //Attenion!!
RTC_Time=(3600*stimestructureget.Hours+60*stimestructureget.Minutes+stimestructureget.Seconds)*1000+RTC_SubSeconds;
return RTC_Time;
}
注1:Once call HAL_RTC_GetTimeTime and Date are both locked, 所以,HAL_RTC_GetTime 必须在HAL_RTC_GetDate前面
注2:两个结构体变量要初始化
注3:毫秒的算法,不是直接使用 stimestructureget.SubSeconds ,而是根据stimestructureget.Second,算出占一个TimeUnit的比率,计算时注意是RTC是Count Down,所以其经过的时间是用 Fraction-SubSeconds,最后再换算成毫秒。
最终结果RTC_Time是换算成毫秒的结果
设置唤醒机制
void RTC_WakeUp(uint32_t count)
{
HAL_RTCEx_DeactivateWakeUpTimer(&RtcHandle);
if(count<0xFFFF) // WUCKSEL [2:1] = 10,
{
HAL_RTCEx_SetWakeUpTimer_IT(&RtcHandle, count-1,RTC_WAKEUPCLOCK_CK_SPRE_16BITS);
}
else //RTC_WAKEUPCLOCK_CK_SPRE_17BITS, WUCKSEL [2:1] = 11, 0x10000 is added to WUTR
{
count=count%0xFFFF;
HAL_RTCEx_SetWakeUpTimer_IT(&RtcHandle, count-1,RTC_WAKEUPCLOCK_CK_SPRE_17BITS); //RTC_SPRE_CLK_1Hz(count=second), 17BITS(1~0x1FFFF)(1s ~36 hours)
}
}
According to RM, WUTF occurs (WUT+1) cycles after WUTE is set ,so use "count-1" instead of "count"
唤醒时间长度
函数的参数WakeUpCounter要求:
#define IS_RTC_WAKEUP_COUNTER(COUNTER) ((COUNTER) <= 0xFFFF)
先假设设置RTC_SPRE_CLK = 32768 / (127+1) / (255+1) = 1Hz,即1秒计时,
RTC_WAKEUPCLOCK_CK_SPRE_16BITS:
唤醒时间长度范围:0x0000 ~ 0xFFFF
那么HAL_RTCEx_SetWakeUpTimer_IT最多只能计时0xFFFF=65535s,约18个小时
RTC_WAKEUPCLOCK_CK_SPRE_17BITS:
在该模式下,实际的计时时间是输入的值加上0x1 0000,
唤醒时间长度范围:0x1 0000 ~ 0x1 FFFF
那么HAL_RTCEx_SetWakeUpTimer_IT最多能计时约36个小时
唤醒时间设置
起初调用HAL_RTCEx_SetWakeUpTimer_IT函数时使用如下的代码
HAL_RTCEx_SetWakeUpTimer_IT(&RtcHandle, count, RTC_WAKEUPCLOCK_CK_SPRE_16BITS);
实际运行时,发现每次都延迟一秒才唤醒,查看该函数的内容:
/* Configure the Wakeup Timer counter */
hrtc->Instance->WUTR = (uint32_t)WakeUpCounter;
又查看参考手册:
The first assertion of WUTF occurs (WUT+1) ck_wut cycles after WUTE is set.
得出,函数的参数是从0开始计的,所以我在配置我的RTC_TimeGet函数时,输入的count,先减1,再赋给HAL_RTCEx_SetWakeUpTimer_IT函数
网友评论