注意:代码在工具链版本 8.4.0 上运行良好,但在 12.2.0 版本上运行不佳
串口终端输出:
System time set to 04:20
Updated time (read using localtime()): 23:59
重现问题的示例代码:
#include <Arduino.h>
#include <stdio.h>
#include <time.h>
#include <sys/time.h>
void setup()
{
Serial.begin(115200);
// Set the desired time (4:20)
struct tm localTime;
localTime.tm_hour = 4;
localTime.tm_min = 20;
// Set the system time
struct timeval newTime = { .tv_sec = mktime(&localTime), .tv_usec = 0 };
if (settimeofday(&newTime, NULL) == 0) {
printf("System time set to 04:20\n");
// Read the updated time
struct tm* updatedLocalTime = localtime(&newTime.tv_sec);
printf("Updated time (read using localtime()): %02d:%02d\n", updatedLocalTime->tm_hour, updatedLocalTime->tm_min);
} else {
perror("Error setting system time");
}
}
您需要初始化
localTime
。现在它的字段具有不确定的值,这使得程序具有未定义的行为,因为这些字段是由 mktime
读取的。您可以先用当前时间填充它,然后更改您想要更改的成员。
示例:
time_t now = time(NULL);
struct tm localTime = *localtime(&now); // initialize with current time
localTime.tm_hour = 4;
localTime.tm_min = 20;
localTime.tm_isdst = -1;
struct timeval newTime = { .tv_sec = mktime(&localTime), .tv_usec = 0 };