NTP - 通过 NTPClient 库检索时间界 (UTC)

材料准备

  • AmebaD [AMB21 / AMB22 / AMB23 / BW16] x 1

范例说明

In this example, we use an NTP client to sync with NTP servers using UDP and keep track of time locally. Open the example. “File” “Examples”→ “NTPClient” “Advanced”

image1

修改标注的代码部分(ssid,password)以连接到您的WiFi网络。

image2

编译代码并将其上传到Ameba。按下“重置”按钮后,Ameba连接到WiFi,从NTP服务器获取UTC时间,并以时区偏移量输出当前时间到serial monitor。

image3

程式码说明

配置NTP客户端:
The NTPClient needs to use a UDP client for communications. A WiFiUDP client is declared and passed to the NTPClient constructor, along with an NTP server address, time zone offset in seconds, and update interval in milliseconds. If detailed configuration is not needed, just passing in the UDP client is also sufficient, refer to the “NTPClient” → “Basic” example.
WiFiUDP ntpUDP;
NTPClient timeClient(ntpUDP, "europe.pool.ntp.org", 3600, 60000);
启动NTP客户端:
连接到WiFi后,将使用 begin() 函数启动NTPClient,这将导致客户端与NTP服务器同步并获取UTC时间。
WiFiUDP ntpUDP;
timeClient.begin();
获取当地时间:
getFormattedTime() 用于将接收到的UTC时间格式化为本地时区。每个循环呼叫 update(),以便NTPClient将在每个更新间隔与NTP服务器同步一次。
timeClient.update();
timeClient.getFormattedTime();