ESP8266 NTP configTime
之前考統測時想要有一個能夠倒數幾天的機器,然而能夠準確的計時剩幾天就是一個大問題,所以決定使用帶有wifi功能的Nodemcu(使用Arduino IDE開發)來上網連接NTP網路對時,這樣就免去了去使用RTC時間晶片的不確定性,能夠更準確地來計時這樣。
首先我們需要用到<Time.h>模組,這裡詳細用法原理請直接參考
在GitHub下載涵式庫
https://github.com/PaulStoffregen/Time
這個程式寫法參照的出處
https://github.com/jumejume1/NodeMCU_ESP8266/blob/master/READ_TIME_FROM_INTERNET/READ_TIME_FROM_INTERNET.ino
這個程式寫法參照的出處
https://github.com/jumejume1/NodeMCU_ESP8266/blob/master/READ_TIME_FROM_INTERNET/READ_TIME_FROM_INTERNET.ino
!!!程式沒有閏年閏月修正功能!!!
#include <ESP8266WiFi.h> #include <time.h> #include <ESP8266WiFiMulti.h> ESP8266WiFiMulti wifiMulti; boolean connectioWasAlive = true; int timezone = 8 * 3600;//時區+8(GMT+8) int dst = 0;
boolean leap_year; const int month_day[]={31,28,31,30,31,30,31,31,30,31,30,31};
const int leap_month_day[]={31,29,31,30,31,30,31,31,30,31,30,31};int target[]={2019,5,31};//設定倒數日期 int date_now[3]; void setup() { Serial.begin(115200); Serial.println(); WiFi.mode(WIFI_STA); WiFi.hostname("esp8266"); Serial.print("Wifi connecting "); wifiMulti.addAP("yourSSID","password"); wifiMulti.addAP("your_second_SSID","second_password");//備用AP while(wifiMulti.run() != WL_CONNECTED){ delay(100); Serial.print('.'); } Serial.printf(" connected to %s\n", WiFi.SSID().c_str()); Serial.println(); Serial.println("Wifi Connected Success!"); Serial.print("NodeMCU IP Address : "); Serial.println(WiFi.localIP() ); configTime(timezone, dst, "pool.ntp.org","time.nist.gov"); Serial.println("\nWaiting for Internet time"); while(!time(nullptr)){ Serial.print("*"); delay(1000); } Serial.println("\nTime response....OK");
}
void loop() { monitorWiFi(); int days=0; time_t now = time(nullptr); struct tm* p_tm = localtime(&now); date_now[0]=p_tm->tm_year + 1900; //今天幾年 date_now[2]=p_tm->tm_mday;//今天幾號 date_now[1]=p_tm->tm_mon + 1; //今天幾月
int months=((12+target[1])-date_now[1])%12; for(int i=0;i!=months;i++){ //arr從零開始,扣1 days=month_day[(date_now[1]+i-1)%12]+days; }
int number=days+target[2]-date_now[2];void monitorWiFi(){ //wifi連線設定 wifiMulti.run(); if (wifiMulti.run() != WL_CONNECTED){ if (connectioWasAlive == true){ connectioWasAlive = false; Serial.print("Looking for WiFi "); } Serial.print("."); delay(500); } else if (connectioWasAlive == false){ connectioWasAlive = true; Serial.printf(" connected to %s\n", WiFi.SSID().c_str()); Serial.print("IP address"); Serial.println(WiFi.localIP()); } }Serial.print(number); //剩幾天
}
留言
張貼留言