【ESP-IDF】使用SNTP进行时间同步

/**
 * @description: sntp初始化
 * @return {*}
 * @note: 参考官方博客
 */
static void esp_initialize_sntp(void)
{
    ESP_LOGI(TAG, "Initializing SNTP");
    sntp_setoperatingmode(SNTP_OPMODE_POLL);
    sntp_setservername(0, "ntp1.aliyun.com");
    sntp_setservername(1, "210.72.145.44");		// 国家授时中心服务器 IP 地址
    sntp_setservername(2, "1.cn.pool.ntp.org");        

    sntp_init();
}

/**
 * @description: 获取时间函数,应用层直接调用即可
 * @return {*}
 * @note: 参考官方博客
 */
static void esp_wait_sntp_sync(void)
{
    char strftime_buf[64];
    esp_initialize_sntp();

    // wait for time to be set
    time_t now = 0;
    struct tm timeinfo = { 0 };
    int retry = 0;

    while (timeinfo.tm_year < (2019 - 1900))
    {
        ESP_LOGD(TAG, "Waiting for system time to be set... (%d)", ++retry);
        vTaskDelay(100 / portTICK_PERIOD_MS);   // 延迟100ms
        time(&now);                             // 获得unix时间戳
        localtime_r(&now, &timeinfo);           // 将unix时间戳转换成struct tm格式
    }

    // set timezone to China Standard Time 设置东八区
    setenv("TZ", "CST-8", 1);
    tzset();

    strftime(strftime_buf, sizeof(strftime_buf), "%Y-%m-%d %H:%M:%S", &timeinfo);   // 修改时间格式
    ESP_LOGI(TAG, "The current date/time in Shanghai is: %s", strftime_buf);
}

/**
 * @description: 获得实时时间
 * @return {*}
 * @note: 
 */
static void display_time(void)
{
    char strftime_buf[64];
    struct tm timeinfo;
    time_t now = 0;

    // Set timezone to China Standard Time
    setenv("TZ", "CST-8", 1);
    tzset();

    while (1)
    {
        time(&now);

        localtime_r(&now, &timeinfo);
        strftime(strftime_buf, sizeof(strftime_buf), "%Y-%m-%d %H:%M:%S", &timeinfo);
        ESP_LOGI(TAG, "The current date/time in Shanghai is: %s", strftime_buf);
        
        vTaskDelay(300 / portTICK_RATE_MS);
    }
}

官方文档_System Time
官方博客_SNTP时间同步
SNTP官方例程

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值