平台:STM32F4
编译器:arm-none-eabi-gcc
- 定义全局变量
time_t time_dat;
- 重定义time()函数
time_t time (time_t *_timer)
{
struct tm *ts;
if(_timer != NULL)
{
time_dat = *_timer;
ts = localtime (_timer);
RTC_Set_Time(ts->tm_hour, ts->tm_min, ts->tm_sec);
RTC_Set_Date(ts->tm_year+1900-2000, ts->tm_mon+1, ts->tm_mday);
}
return time_dat;
}
- 在秒中断中累加time_dat
我是在WakeUp中断回调函数中累加
void HAL_RTCEx_WakeUpTimerEventCallback(RTC_HandleTypeDef *hrtc)
{
time_dat ++;
}
- 读取RTC初始化time_date
需要注意的是tm结构体中月份tm_mon是从0开始的,tm_year是1900年之后的年数。
void timeInit()
{
time_t settime;
struct tm orig;
RTC_TimeTypeDef RTC_TimeStruct;
RTC_DateTypeDef RTC_DateStruct;
HAL_RTC_GetTime(&RTC_Handler, &RTC_TimeStruct, RTC_FORMAT_BIN);
HAL_RTC_GetDate(&RTC_Handler, &RTC_DateStruct, RTC_FORMAT_BIN);
orig.tm_sec = RTC_TimeStruct.Seconds;
orig.tm_min = RTC_TimeStruct.Minutes;
orig.tm_hour = RTC_TimeStruct.Hours;
orig.tm_mday = RTC_DateStruct.Date;
orig.tm_mon = RTC_DateStruct.Month-1;
orig.tm_year = 2000 + RTC_DateStruct.Year - 1900;
orig.tm_isdst = -1;
settime = mktime (&orig);
time(&settime);
}
- 使用time
time_t now;
struct tm *ts;
char buf [80];
now = time (NULL);
ts = localtime (& now);
strftime (buf, sizeof (buf), "%a %Y-%m-%d %H:%M:%S %Z", ts);
printf_safe("%s \n", buf);