Arduino 時間庫簡介
時間庫為您提供了 Arduino 上的時間保持功能。該庫的最新版本已在 此處 記錄。
要安裝它,請在庫管理器中搜索 Time 並安裝 Michael Margolis 的庫。您需要滾動一下才能找到此庫。
安裝庫後,如果轉到**檔案 → 示例 → 時間**,您將能夠看到將此庫與各種來源整合的幾個示例:GPS、NTP、RTC 等。
基本思想是您可以使用以下函式設定時間:
setTime(hours, minutes, seconds, days, months, years);
或者,
setTime(t);
其中**t** 是特殊**time_t** 變數型別,它是自 1970 年以來經過的秒數。您可能也將其稱為紀元時間。
或者,您可以設定同步源**setSyncProvider(getTimeFunction)** 和同步間隔**setSyncInterval(seconds)**。這樣,如果您有一個具有**getTime()** 函式的源,則可以將其用作同步源並每隔 N 秒(在**setSyncInterval** 引數中指定)更新一次時間。TimeRTC 示例中給出了一個說明。
透過以上任何一種方式設定時間後,時間庫使用內部**millis()** 函式來維護時間。
示例
例如,在以下程式碼中,我在 setup 中設定了一個任意的時間值,並且我每隔 1 秒在迴圈中列印一次時間值。
#include <TimeLib.h> void setup() { // put your setup code here, to run once: Serial.begin(9600); Serial.println(); setTime(3, 10, 30, 24, 5, 2021); } void loop() { // put your main code here, to run repeatedly: digitalClockDisplay(); delay(1000); } void digitalClockDisplay(){ // digital clock display of the time Serial.print(hour()); printDigits(minute()); printDigits(second()); Serial.print(" "); Serial.print(day()); Serial.print(" "); Serial.print(month()); Serial.print(" "); Serial.print(year()); Serial.println(); } void printDigits(int digits) { // utility function for digital clock display: prints preceding colon and leading 0 Serial.print(":"); if(digits < 10) Serial.print('0'); Serial.print(digits); }
輸出
序列埠監視器輸出為:
如您所見,時間每秒遞增。因此,一旦設定了時間,此庫就可以維護它,最好的部分是它可以與各種時間源(如 GPS、RTC、NTP 等)介面。建議您仔細閱讀此庫的文件以及隨此庫附帶的示例。
廣告