我正在编写代码来生成时间戳,以将其用作执行特定功能的参考。 任何人都可以帮助我如何做到这一点。 我是嵌入式编程的新手。
答案 0 :(得分:1)
首先,你必须初始化RTC。希望你知道,如何做这个STM32CubeMX。
然后是简单的代码:
#include <time.h>
/* Global Vars */
RTC_TimeTypeDef currentTime;
RTC_DateTypeDef currentDate;
time_t timestamp;
struct tm currTime;
/* Code to get timestamp
*
* You must call HAL_RTC_GetDate() after HAL_RTC_GetTime() to unlock the values
* in the higher-order calendar shadow registers to ensure consistency between the time and date values.
* Reading RTC current time locks the values in calendar shadow registers until Current date is read
* to ensure consistency between the time and date values.
*/
HAL_RTC_GetTime(&hrtc, ¤tTime, RTC_FORMAT_BIN);
HAL_RTC_GetDate(&hrtc, ¤tDate, RTC_FORMAT_BIN);
currTime.tm_year = currentDate.Year + 100; // In fact: 2000 + 18 - 1900
currTime.tm_mday = currentDate.Date;
currTime.tm_mon = currentDate.Month - 1;
currTime.tm_hour = currentTime.Hours;
currTime.tm_min = currentTime.Minutes;
currTime.tm_sec = currentTime.Seconds;
timestamp = mktime(&currTime);
P.S。我不检查日期和时间数据是否正确。如果你想 - 自己做一些正确的数据检查。
答案 1 :(得分:0)