最近因為某些原因有用到網路時間的東西,所以記錄了一下
有需要的話直接程式碼複製貼上就可以看到網路時間了,下面另外把它存成字串顯示出來,如果另外有需求的話直接改也很簡單
#include <WiFi.h>
//#include "time.h"
const char* ssid = "輸入你的熱點名稱";
const char* password = "輸入你的熱點密碼";
const char* ntpServer = "pool.ntp.org";
const long gmtOffset_sec = 28800;//格林威治時間,一格3600,GMT+8就是8*3600=28800
const int daylightOffset_sec = 3600;
void setup(){
Serial.begin(115200);
// Connect to Wi-Fi
Serial.print("Connecting to ");
Serial.println(ssid);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi connected.");
// Init and get the time
configTime(gmtOffset_sec, daylightOffset_sec, ntpServer);
printLocalTime();
//disconnect WiFi as it's no longer needed
WiFi.disconnect(true);//連上拿到時間資料後就切斷連線
WiFi.mode(WIFI_OFF);
}
void loop(){
delay(1000);
printLocalTime();
}
void printLocalTime(){
struct tm timeinfo;
if(!getLocalTime(&timeinfo)){
Serial.println("Failed to obtain time");
return;
}
Serial.println(&timeinfo, "%A, %B %d %Y %H:%M:%S");//參考C++的strftime語法就會知道為甚麼這樣寫
Serial.print("Day of week: ");
Serial.println(&timeinfo, "%A");
Serial.print("Month: ");
Serial.println(&timeinfo, "%B");
Serial.print("Day of Month: ");
Serial.println(&timeinfo, "%d");
Serial.print("Year: ");
Serial.println(&timeinfo, "%Y");
Serial.print("Hour: ");
Serial.println(&timeinfo, "%H");
Serial.print("Hour (12 hour format): ");
Serial.println(&timeinfo, "%I");
Serial.print("Minute: ");
Serial.println(&timeinfo, "%M");
Serial.print("Second: ");
Serial.println(&timeinfo, "%S");
Serial.println("TEST variables");//抓取時間資料裡的"小時"存成字串做測試,以便後續應用
char myHour[3];
strftime(myHour,3, "%H", &timeinfo);
Serial.println(myHour);
String A = String(myHour);
Serial.println(A);
}
下圖是執行結果:
留言列表