esp-idf手动设置系统时间

6 篇文章 0 订阅
2 篇文章 1 订阅

官方提到使用ntp同步时间,后自动设置了时间。

System Time - ESP32 - — ESP-IDF 编程指南 v4.3.1 文档icon-default.png?t=LA92https://docs.espressif.com/projects/esp-idf/zh_CN/v4.3.1/esp32/api-reference/system/system_time.html使用了函数settimeofday().

To set the current time, you can use the POSIX functions settimeofday() and adjtime()

这里直接手动设置时间,参考arduino第三方库esp32time的写法。

#include <time.h>
#include <sys/time.h>
//houyawei
void setTime(int sc, int mn, int hr, int dy, int mt, int yr) {
    // seconds, minute, hour, day, month, year $ microseconds(optional)
    // ie setTime(20, 34, 8, 1, 4, 2021) = 8:34:20 1/4/2021
    struct tm t = {0};        // Initalize to all 0's
    t.tm_year = yr - 1900;    // This is year-1900, so 121 = 2021
    t.tm_mon = mt - 1;
    t.tm_mday = dy;
    t.tm_hour = hr;
    t.tm_min = mn;
    t.tm_sec = sc;
    time_t timeSinceEpoch = mktime(&t);
    //   setTime(timeSinceEpoch, ms);
    struct timeval now = { .tv_sec = timeSinceEpoch };
    settimeofday(&now, NULL);
//houyawei
}

调用的时候,直接

setTime(20,34,8,1,4,2021);

读取可以直接按照官方写的例子

time_t now;
char strftime_buf[64];
struct tm timeinfo;

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

localtime_r(&now, &timeinfo);
strftime(strftime_buf, sizeof(strftime_buf), "%c", &timeinfo);
//ESP_LOGI(TAG, "The current date/time in Shanghai is: %s", strftime_buf);
puts(strftime_buf);
//也可以只取出年月日等参数
/×
timeinfo.tm_year
timeinfo.tm_mon  
timeinfo.tm_mday
timeinfo.tm_hour
timeinfo.tm_min
timeinfo.tm_sec
houyawei
×/

参考:

System Time - ESP32 - — ESP-IDF 编程指南 v4.3.1 文档icon-default.png?t=LA92https://docs.espressif.com/projects/esp-idf/zh_CN/v4.3.1/esp32/api-reference/system/system_time.html

ESP32Time/ESP32Time.cpp at main · fbiego/ESP32Time · GitHubicon-default.png?t=LA92https://github.com/fbiego/ESP32Time/blob/main/ESP32Time.cpp How can I set the date / time? - ESP32 ForumEspressif ESP32 Official Forumhttps://www.esp32.com/viewtopic.php?t=6043

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值