Fork me on github

ESP32使用NTP同步时间

ESP32在连接了WiFi以后,可以使用NTP来校对本机时间,否则默认的Unix时间戳从0开始。代码如下:

#include <esp32-hal.h>
#include <lwip/apps/sntp.h>
#include <stdarg.h>
#include <stdlib.h>
#include <time.h>

/**
 * @brief 设置时区和NTP服务器和并校对时间
 * @param [in] posix_tz 表示posix规范的时间戳。例如"UTC-8"表示东八区(北京时间)
 * @param [in] server_cnt NTP服务器的数量,超过三个的会被抛弃
 * @param [in] ... NTP服务器,C风格字符串指针类型,数量应与server_cnt对应
 * @attention 函数不会保证WiFi连接正常
 * @example set_time("UTC-8", 3, "time2.cloud.tencent.com", "ntp1.aliyun.com", "ntp.ntsc.ac.cn");
 * @example set_time("UTC+6", 2, "time2.cloud.tencent.com", "192.168.0.2");
 */
void set_time(const char *const posix_tz, const int server_cnt, ...)
{
	sntp_setoperatingmode(SNTP_OPMODE_POLL);
	va_list ap;
	va_start(ap, server_cnt);
	if (server_cnt > 3)        // sntp_setservername最多支持3个地址
		server_cnt = 3;    // 超过三个的地址会被抛弃
	for (int i = 0; i < server_cnt; ++i)
		sntp_setservername(i, va_arg(ap, char *));
	va_end(ap);
	sntp_init();
	setenv("TZ", posix_tz, 1);
	tzset();
	while (time(NULL) < 1580000000) // 阻塞,直到时间同步
		yield();
	sntp_stop();
}

在使用时,我们可以这样调用函数:

set_time("UTC-8", 3, "time2.cloud.tencent.com", "ntp1.aliyun.com", "ntp.ntsc.ac.cn");
posted @ 2020-04-20 16:48  fang-d  阅读(5703)  评论(0编辑  收藏  举报