MCU获取时间

MCU获取时间

本文收录MCU获取网络时间的各种不同方式。

1.ESP8266/8285

使用ESP8266/8285获取时间共有以下方式

  1. 通过NTP获取网络时间

    需要的库

    • ESP8266WiFi.h
    • WiFiUdp.h
    • NTPClient.h(可通过 Arduino 库管理器安装)

    示例代码

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    #include <ESP8266WiFi.h>
    #include <WiFiUdp.h>
    #include <NTPClient.h>

    // 替换为你自己的 WiFi 信息
    const char* ssid = "your_SSID";
    const char* password = "your_PASSWORD";

    // 创建 UDP 实例
    WiFiUDP ntpUDP;

    // 创建 NTP 客户端,偏移秒数(如北京时间为 +8 小时 = 8 * 3600 = 28800 秒)
    NTPClient timeClient(ntpUDP, "pool.ntp.org", 28800, 60000); // 每分钟更新一次

    void setup() {
    WiFi.begin(ssid, password);
    while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    }
    timeClient.begin();
    }

    void loop() {
    timeClient.update();
    timeClient.getFormattedTime()// 返回格式为 HH:MM:SS
    delay(1000);
    }