以下是一个基于 ESP32 - S3 同步 NTP(网络时间协议)并获取系统时间的 C 语言程序例程。这个例程使用了 ESP-IDF(Espressif IoT Development Framework)来实现,你需要在 ESP-IDF 环境下编译和运行该程序。
#include <stdio.h>
#include <time.h>
#include <sys/time.h>
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "esp_system.h"
#include "esp_log.h"
#include "nvs_flash.h"
#include "esp_netif.h"
#include "esp_event.h"
#include "protocol_examples_common.h"
#include "lwip/apps/sntp.h"
static const char *TAG = "ntp_example";
// 初始化 SNTP(简单网络时间协议)
static void initialize_sntp(void)
{
ESP_LOGI(TAG, "Initializing SNTP");
sntp_setoperatingmode(SNTP_OPMODE_POLL);
sntp_setservername(0, "pool.ntp.org");
sntp_init();
}
// 等待时间同步
static void obtain_time(void)
{
// 初始化网络
ESP_ERROR_CHECK(example_connect());
// 初始化 SNTP
initialize_sntp();
// 等待时间同步
time_t now = 0;
struct tm timeinfo = { 0 };
int retry = 0;
const int retry_count = 10;
while (sntp_get_sync_status(

最低0.47元/天 解锁文章
5287

被折叠的 条评论
为什么被折叠?



