SNTP获取网络时间
前提要求
SNTP需要网络连接,首次启动需等待网络就绪,因此必须配置连接WIFI。
需要包括头文件#include "esp_netif.h"和#include "esp_log.h"其他头文件按需添加!
在main/CMakeLists.txt中的PRIV_REQUIRES中加入额外的esp_timer esp_netif
配置SNTP
Component config → LWIP → SNTP →
[*] Enable SNTP module
Maximum number of NTP servers: 3
Request interval (ms): 60000 (1分钟)
SNTP服务初始化
static void set_timezone(void)
{
// 设置中国标准时间(北京时间)
setenv("TZ", "CST-8", 1);
tzset();
ESP_LOGI(TAG, "时区设置为北京时间 (CST-8)");
}
static time_t get_current_time(void)
{
// 使用POSIX函数获取时间
return time(NULL);
}
static void print_current_time(void)
{
time_t now = get_current_time();
struct tm timeinfo;
char buffer[64];
localtime_r(&now, &timeinfo);
strftime(buffer, sizeof(buffer), "%Y-%m-%d %H:%M:%S %A", &timeinfo);
ESP_LOGI(TAG, "当前时间: %s", buffer);
}
static void initialize_sntp(void)
{
ESP_LOGI(TAG, "初始化SNTP服务");
#if ESP_IDF_VERSION >= ESP_IDF_VERSION_VAL(5, 0, 0)
// 设置时间服务器(默认使用 pool.ntp.org)
esp_sntp_setoperatingmode(SNTP_OPMODE_POLL);
// 添加 NTP 服务器
// esp_sntp_setservername(0, "pool.ntp.org"); // 默认服务器
esp_sntp_setservername(0, "cn.pool.ntp.org"); // 中国 NTP 服务器
esp_sntp_setservername(1, "ntp1.aliyun.com"); // 阿里云 NTP 服务器
// 初始化 SNTP
esp_sntp_init();
#else
sntp_setoperatingmode(SNTP_OPMODE_POLL);
// esp_sntp_setservername(0, "pool.ntp.org"); // 默认服务器
esp_sntp_setservername(0, "cn.pool.ntp.org"); // 中国 NTP 服务器
esp_sntp_setservername(1, "ntp1.aliyun.com"); // 阿里云 NTP 服务器
sntp_init(); // 初始化 SNTP
#endif
set_timezone();// 设置时区
print_current_time(); 打印时间
}
之后将这个初始化放在WIFI连接函数之后,在主循环之前,执行initialize_sntp(); // 初始化 SNTP
运行结果
构建编译烧录下载至目标芯片!串口显示:
I (586) main: 初始化SNTP服务
I (586) main: 时区设置为北京时间 (CST-8)
I (596) main: 当前时间: 2026-01-24 21:40:18 Saturday
评论
暂无评论