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();