Last active
March 30, 2020 05:55
-
-
Save clive520/a4f38e3f68d1026bda530147793821f7 to your computer and use it in GitHub Desktop.
ESP8266_取得網路時間並轉換成數字int
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <ESP8266WiFi.h> | |
#include "esp_NTPClient.h" | |
#include <WiFiUdp.h> | |
//宣告變數 | |
String T_Time = ""; | |
String T_Time_STR = "" ; | |
int H01=0; //H01代表小時的個位數 | |
int H10=0; //H10代表小時的十位數 | |
int HH=0; //HH代表小時的數量 | |
int M01=0; //M01代表分鐘的個位數 | |
int M10=0; //M10代表分鐘的十位數 | |
int MM=0; //MM代表分鐘的數量 | |
//開啟wifi | |
WiFiUDP ntpUDP; | |
NTPClient timeClient(ntpUDP); | |
void setup() | |
{ | |
Serial.begin(9600); | |
//連接wifi | |
WiFi.begin("Free","ruby3217"); | |
while(WiFi.status() != WL_CONNECTED) { | |
delay(500); | |
Serial.print("."); | |
} | |
//取得網路時間必須要放 | |
timeClient.begin(); | |
timeClient.setTimeOffset(28800); | |
Serial.println(WiFi.localIP()); | |
} | |
void loop() //主程式 | |
{ | |
get_time(); | |
delay(5000); | |
} | |
//副程式 | |
//取得網路時間,轉成數字,H10代表小時的十位數,H01代表小時的個位數,HH代表小時 | |
//M10代表分鐘的十位數,M01代表分鐘的個位數,MM代表小時 | |
void get_time() { | |
timeClient.update(); | |
T_Time = timeClient.getFormattedTime(); | |
Serial.println(T_Time); | |
T_Time_STR = T_Time.charAt(0); | |
H10 = T_Time_STR.toInt(); | |
T_Time_STR = T_Time.charAt(1); | |
H01 = T_Time_STR.toInt(); | |
HH = H10 * 10 + H01; | |
T_Time_STR = T_Time.charAt(3); | |
M10 = T_Time_STR.toInt(); | |
T_Time_STR = T_Time.charAt(4); | |
M01 = T_Time_STR.toInt(); | |
MM = M10 * 10 + M01; | |
Serial.println((String("1=") + String(H10) + String(" 2=") + String(H01) + String(" HH=") + String(HH))); | |
Serial.println((String("4=") + String(M10) + String(" 5=") + String(M01) + String(" MM=") + String(MM))); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment