C标准时间函数库头文件:
数据结构:
1 2 3 4 5 6 7 8 9 10 11
| struct tm { int tm_sec; int tm_min; int tm_hour; int tm_mday; int tm_mon; int tm_year; int tm_wday; int tm_yday; int tm_isdst; };
|
由于HAL库默认使用了SysTick定时器为时基,并且一般是1ms中断一次,所以我们可以利用该定时器实现秒前进,需要覆写该函数:
1 2 3 4 5 6 7 8 9 10 11 12
| volatile uint32_t time_dat = 0;
void HAL_IncTick(void) { static uint32_t ticks = 0; uwTick += uwTickFreq; ticks = (ticks + 1) % 1000; if(!ticks) { time_dat++; } }
|
然后重新实现time()函数:
1 2 3 4 5 6 7 8
| time_t time (time_t *_timer) { if(_timer != NULL) { time_dat = *_timer; } return time_dat; }
|
示例使用代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49
| time_t tim; struct tm *ts; struct tm ctime;
ctime.tm_year = 2021 - 1900; ctime.tm_mon = 12 - 1; ctime.tm_mday = 30; ctime.tm_hour = 10; ctime.tm_min = 24; ctime.tm_sec = 51; tim = mktime(&ctime);
time(&tim);
tim = time(NULL);
ts = localtime(&tim);
printf(" %04d-%02d-%02d %02d:%02d:%02d \r\n", ts->tm_year + 1900, ts->tm_mon + 1, ts->tm_mday, ts->tm_hour, ts->tm_min, ts->tm_sec);
while (1) { tim = time(NULL);
ts = localtime(&tim);
printf(" %04d-%02d-%02d %02d:%02d:%02d \r\n", ts->tm_year + 1900, ts->tm_mon + 1, ts->tm_mday, ts->tm_hour, ts->tm_min, ts->tm_sec); HAL_Delay(1000); }
|
————————————————
版权声明:本文为CSDN博主「觉皇嵌入式」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/qq153471503/article/details/122231112