GET /apps/thingtweet/1/statuses/update?api_key=ThingTweet識別碼&status=要傳送的推特訊息
完整的程式如下 :
#include <SoftwareSerial.h>
#define DEBUG true
SoftwareSerial esp8266(7,8); //(RX,TX) String ThingTweet_API="B2B4JF5WEUXGCOUY";
int i=0; //counter
void setup() {
Serial.begin(9600);
esp8266.begin(9600);
sendData("AT+RST\r\n",2000,DEBUG); // reset ESP8266
sendData("AT+GMR\r\n",1000,DEBUG);
delay(3000); //wait for wifi connection to get local ip
sendData("AT+CIFSR\r\n",1000,DEBUG); //get ip address
}
void loop() {
Serial.println("Connecting Thingspeak ..."); sendData("AT+CIPSTART=\"TCP\",\"api.thingspeak.com\",80\r\n",1000,DEBUG); String data="GET /apps/thingtweet/1/statuses/update?api_key=" + ThingTweet_API + "&status=Hello! " + i + " times.\r\n"; sendData("AT+CIPSEND=" + (String)data.length() + "\r\n",1000,DEBUG); String res=sendData(data,3000,DEBUG); res.replace("\r\n",""); //remove all line terminator if (res.indexOf("Unlink") == -1) { //if no auto unlink sendData("AT+CIPCLOSE\r\n",2000,DEBUG); //close session } delay(60000);
i++;
}
String sendData(String command, const int timeout, boolean debug) {
String res="";
esp8266.print(command);
long int time=millis();
while ((time + timeout) > millis()) {
while(esp8266.available()) {res.concat((char)esp8266.read());}
}
if (debug) {Serial.print(res);}
return res;
}
void setup() {
Serial.begin(9600);
esp8266.begin(9600);
sendData("AT+RST\r\n",2000,DEBUG); // reset ESP8266 while (!connectWifi(ssid, pwd)) { Serial.println("Connecting WiFi ... failed"); delay(2000); }
sendData("AT+GMR\r\n",1000,DEBUG);
delay(3000); //wait for wifi connection to get local ip
sendData("AT+CIFSR\r\n",1000,DEBUG); //get ip address
}
void loop() {
Serial.println("Connecting Thingspeak ...");
sendData("AT+CIPSTART=\"TCP\",\"api.thingspeak.com\",80\r\n",1000,DEBUG);
String data="GET /apps/thingtweet/1/statuses/update?api_key=" + ThingTweet_API +
"&status=Hello! " + i + " times.\r\n";
sendData("AT+CIPSEND=" + (String)data.length() + "\r\n",1000,DEBUG);
String res=sendData(data,3000,DEBUG);
res.replace("\r\n",""); //remove all line terminator
if (res.indexOf("Unlink") == -1) { //if no auto unlink
sendData("AT+CIPCLOSE\r\n",2000,DEBUG); //close session
}
delay(60000);
i++;
}
void setup() {
Serial.begin(9600);
esp8266.begin(9600);
sendData("AT+RST\r\n",2000,DEBUG); // reset ESP8266
sendData("AT+GMR\r\n",1000,DEBUG);
delay(3000); //wait for wifi connection to get local ip
sendData("AT+CIFSR\r\n",1000,DEBUG); //get ip address
Serial.println("Sending request to NTP server ...");
sync_clock();
Alarm.timerRepeat(60, sync_clock);
lcd.begin(16,2); //define 2*16 LCD
lcd.clear(); //clear screen
}
void loop() {
String d=getDate();
String t=getTime();
String w=getWeek();
Serial.println(d + " " + t + " " + w);
lcd.setCursor(0,0); //move to (x,y)
lcd.print(d); //print date
lcd.setCursor(11,0); //move to (x,y)
lcd.print(w); //print date
lcd.setCursor(0,1); //move to (x,y)
lcd.print(t); //print date
Alarm.delay(1000);
}
long getCST() {
//Start UDP Rrequest to NTP Server 91.226.136.136, 82.209.243.241,192.5.41.40
//132.163.4.101, 132.163.4.102, 132.163.4.103
sendData("AT+CIPSTART=\"UDP\",\"91.226.136.136\",123\r\n",5000,DEBUG);
memset(packetBuffer,0,128); //clear buffer
packetBuffer[0]=0xE3; //LI, Version, Mode
packetBuffer[1]=0x00; //Stratum, or type of clock
packetBuffer[2]=0x06; //Polling Interval
packetBuffer[3]=0xEC; //Peer Clock Precision
packetBuffer[12]=0x31; //reference ID (4 bytes)
packetBuffer[13]=0x4E;
packetBuffer[14]=0x31;
packetBuffer[15]=0x34;
//send request to NTP Server
sendData("AT+CIPSEND=48\r\n",1000,DEBUG); //send data length
for (byte i=0; i < 48; i++) {
esp8266.write(packetBuffer[i]);
delay(5);
}
//deal with NTP response
memset(packetBuffer,0,128); //clear buffer to store NTP response
Serial.println();
Serial.println("NTP server answered : ");
int i=0; //packet byte counter
while (esp8266.available() > 0) { //if receive NTP response : fall in loop
byte ch=esp8266.read(); //got NTP response, read one byte for each loop
if (i < 128) {packetBuffer[i]=ch;} //store received byte to packet buffer
//show receving bytes in hex
if (ch < 0x10) {Serial.print('0');} //prefix with '0' if byte value 0~9
Serial.print(ch, HEX);
Serial.print(' ');
if ((((i+1) % 10) == 0)) {Serial.println();} //newline if exceeds 10 bytes
delay(5); //wait 5ms for next incoming byte
i++; //increment packet byte counter
if ((i < 104) && (esp8266.available() == 0)) { //wainting if lags
//Response packets not enough but no response : wait 1.5 seconds
byte wcount=0; //waiting counter
while (esp8266.available() == 0) { //loop until timeout (1.5 seconds)
Serial.print("!"); //show ! means waiting for response packet
delay(100);
wcount += 1; //increment waiting counter
if (wcount >= 15) {break;} //waiting timeout : quit loop
}
}
}
Serial.println();
Serial.println();
Serial.print(i+1);
Serial.println(" bytes received"); // will be more than 48
//Show time stamp (locates from byte 101~104 of the response packet)
Serial.print("NTP time stamp packets (byte 101~104)=");
Serial.print(packetBuffer[101],HEX);
Serial.print(" ");
Serial.print(packetBuffer[102],HEX);
Serial.print(" ");
Serial.print(packetBuffer[103],HEX);
Serial.print(" ");
Serial.print(packetBuffer[104],HEX);
Serial.println();
//handling time packets (4 bytes long) : combine them into words
unsigned long highWord=word(packetBuffer[101],packetBuffer[102]);
unsigned long lowWord=word(packetBuffer[103],packetBuffer[104]);
//shift high word 16 bits left & OR with low word to form a double word
//the result is a NTP time stamp (seconds since Jan 1 1900):
unsigned long secsSince1900=highWord << 16 | lowWord;
Serial.print("NTP time stamp (seconds since 1900-01-01)=");
Serial.println(secsSince1900);
//convert NTP time stamp to Unix time stamp :
//Unix time starts on Jan 1 1970=2208988800 seconds since 1900-01-01
//subtract seventy years to get Unix time stamp, plus 28800 (UTC+8)
unsigned long epoch=secsSince1900 - 2208988800UL;
Serial.print("Unix time stamp (seconds since 1970-01-01)=");
Serial.println(epoch); //print Unix time
sendData("AT+CIPCLOSE\r\n",1000,DEBUG); //close session
return epoch + 28800;
}
String sendData(String command, const int timeout, boolean debug) {
String response="";
esp8266.print(command); // send the read character to the esp8266
long int time=millis();
while ((time+timeout) > millis()) {
while(esp8266.available()) {
// The esp has data so display its output to the serial window
char c=esp8266.read(); // read the next character.
response += c;
}
}
if (debug) {Serial.print(response);}
return response;
}
123 bytes received
NTP time stamp packets (byte 101~104)=DB 37 5C 46
NTP time stamp (seconds since 1900-01-01)=3677838406
Unix time stamp (seconds since 1970-01-01)=1468849606
AT+CIPCLOSE
124 bytes received
NTP time stamp packets (byte 101~104)=DB 37 5C 8A
NTP time stamp (seconds since 1900-01-01)=3677838474
Unix time stamp (seconds since 1970-01-01)=1468849674
AT+CIPCLOSE
void setup() {
Serial.begin(9600);
esp8266.begin(9600);
sendData("AT+RST\r\n",2000,DEBUG); // reset ESP8266
sendData("AT+GMR\r\n",1000,DEBUG);
delay(3000); //wait for wifi connection to get local ip
sendData("AT+CIFSR\r\n",1000,DEBUG); //get ip address
Serial.println("Sending request to NTP server ...");
sync_clock();
Alarm.timerRepeat(60, sync_clock);
lcd.begin(16,2); //define 2*16 LCD
lcd.clear(); //clear screen
}
void loop() {
String d=getDate();
String t=getTime();
String w=getWeek();
Serial.println(d + " " + t + " " + w);
lcd.setCursor(0,0); //move to (x,y)
lcd.print(d); //print date
lcd.setCursor(11,0); //move to (x,y)
lcd.print(w); //print date
lcd.setCursor(0,1); //move to (x,y)
lcd.print(t); //print date float h=dht.readHumidity(); //get humidity from DHT11 float c=dht.readTemperature(); //get temperature (C) from DHT11 if (isnan(h) || isnan(c)) {h=0.0;c=0.0;} lcd.setCursor(9,1); //move to (x,y) lcd.print(int(c)); //print celcius lcd.setCursor(11,1); //move to (x,y) lcd.print((char)223); //print degree symbol lcd.setCursor(12,1); //move to (x,y) lcd.print(' '); //print space lcd.setCursor(13,1); //move to (x,y) lcd.print(int(h)); //print humidity lcd.setCursor(15,1); //move to (x,y) lcd.print('%'); //print %
Alarm.delay(1000);
}
long getCST() {
//Start UDP Rrequest to NTP Server 91.226.136.136, 82.209.243.241,192.5.41.40
//132.163.4.101, 132.163.4.102, 132.163.4.103
sendData("AT+CIPSTART=\"UDP\",\"91.226.136.136\",123\r\n",5000,DEBUG);
memset(packetBuffer,0,128); //clear buffer
packetBuffer[0]=0xE3; //LI, Version, Mode
packetBuffer[1]=0x00; //Stratum, or type of clock
packetBuffer[2]=0x06; //Polling Interval
packetBuffer[3]=0xEC; //Peer Clock Precision
packetBuffer[12]=0x31; //reference ID (4 bytes)
packetBuffer[13]=0x4E;
packetBuffer[14]=0x31;
packetBuffer[15]=0x34;
//send request to NTP Server
sendData("AT+CIPSEND=48\r\n",1000,DEBUG); //send data length
for (byte i=0; i < 48; i++) {
esp8266.write(packetBuffer[i]);
delay(5);
}
//deal with NTP response
memset(packetBuffer,0,128); //clear buffer to store NTP response
Serial.println();
Serial.println("NTP server answered : ");
int i=0; //packet byte counter
while (esp8266.available() > 0) { //if receive NTP response : fall in loop
byte ch=esp8266.read(); //got NTP response, read one byte for each loop
if (i < 128) {packetBuffer[i]=ch;} //store received byte to packet buffer
//show receving bytes in hex
if (ch < 0x10) {Serial.print('0');} //prefix with '0' if byte value 0~9
Serial.print(ch, HEX);
Serial.print(' ');
if ((((i+1) % 10) == 0)) {Serial.println();} //newline if exceeds 10 bytes
delay(5); //wait 5ms for next incoming byte
i++; //increment packet byte counter
if ((i < 104) && (esp8266.available() == 0)) { //wainting if lags
//Response packets not enough but no response : wait 1.5 seconds
byte wcount=0; //waiting counter
while (esp8266.available() == 0) { //loop until timeout (1.5 seconds)
Serial.print("!"); //show ! means waiting for response packet
delay(100);
wcount += 1; //increment waiting counter
if (wcount >= 15) {break;} //waiting timeout : quit loop
}
}
}
Serial.println();
Serial.println();
Serial.print(i+1);
Serial.println(" bytes received"); // will be more than 48
//Show time stamp (locates from byte 101~104 of the response packet)
Serial.print("NTP time stamp packets (byte 101~104)=");
Serial.print(packetBuffer[101],HEX);
Serial.print(" ");
Serial.print(packetBuffer[102],HEX);
Serial.print(" ");
Serial.print(packetBuffer[103],HEX);
Serial.print(" ");
Serial.print(packetBuffer[104],HEX);
Serial.println();
//handling time packets (4 bytes long) : combine them into words
unsigned long highWord=word(packetBuffer[101],packetBuffer[102]);
unsigned long lowWord=word(packetBuffer[103],packetBuffer[104]);
//shift high word 16 bits left & OR with low word to form a double word
//the result is a NTP time stamp (seconds since Jan 1 1900):
unsigned long secsSince1900=highWord << 16 | lowWord;
Serial.print("NTP time stamp (seconds since 1900-01-01)=");
Serial.println(secsSince1900);
//convert NTP time stamp to Unix time stamp :
//Unix time starts on Jan 1 1970=2208988800 seconds since 1900-01-01
//subtract seventy years to get Unix time stamp, plus 28800 (UTC+8)
unsigned long epoch=secsSince1900 - 2208988800UL;
Serial.print("Unix time stamp (seconds since 1970-01-01)=");
Serial.println(epoch); //print Unix time
sendData("AT+CIPCLOSE\r\n",1000,DEBUG); //close session
return epoch + 28800;
}
String sendData(String command, const int timeout, boolean debug) {
String response="";
esp8266.print(command); // send the read character to the esp8266
long int time=millis();
while ((time+timeout) > millis()) {
while(esp8266.available()) {
// The esp has data so display its output to the serial window
char c=esp8266.read(); // read the next character.
response += c;
}
}
if (debug) {Serial.print(response);}
return response;
}
把下載下來的 Time-master.zip 檔解壓縮後放到 Arduino IDE 的安裝目錄的 libraries 資料夾下面, 重開 IDE 就會抓到此函式庫了. 在 Arduino Time library 底下有一個範例程式, 我把範例程式整理並加註中文說明如下 :
測試 1 :
#include <Time.h>
#define TIME_MSG_LEN 11 //時間字串長度含標頭 T 為 11 字元 (T+10位數之 Unix 時戳)
#define TIME_HEADER 'T' //時間同步訊息標頭
#define TIME_REQUEST 7 //ASCII bell character requests a time sync message
//時間字串格式 T1262347200 //noon Jan 1 2010
void setup() {
Serial.begin(9600);
}
void loop() {
if (Serial.available()) { //串列埠收到訊息
processSyncMessage(); //處理時間同步字串
}
if (timeStatus() == timeNotSet) { //時間尚未同步
Serial.println("waiting for sync message");
}
else { //時間已同步, 顯示時間
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);
}
SoftwareSerial esp8266(7,8); //(RX,TX)
byte packetBuffer[128]; //buffer : send & recv data to/from NTP
int i=0; //sync cycle counter
void setup() {
Serial.begin(9600);
esp8266.begin(9600);
sendData("AT+RST\r\n",2000,DEBUG); // reset ESP8266
sendData("AT+GMR\r\n",1000,DEBUG); delay(3000); //wait for wifi connection to get local ip
sendData("AT+CIFSR\r\n",1000,DEBUG); //get ip address
Serial.println("Sending request to NTP server ..."); setTime(getTime());
}
void showDateTime() { //輸出如 2016-07-15 19:56:12 格式的日期時間
Serial.print(year());
Serial.print("-");
byte M=month();
if (M < 10) {Serial.print('0');}
Serial.print(M);
Serial.print("-");
byte d=day();
if (d < 10) {Serial.print('0');}
Serial.print(d);
Serial.print(" ");
byte h=hour();
if (h < 10) {Serial.print('0');}
Serial.print(h);
Serial.print(":");
byte m=minute();
if (m < 10) {Serial.print('0');}
Serial.print(m);
Serial.print(":");
byte s=second();
if (s < 10) {Serial.print('0');}
Serial.println(s);
}
long getTime() { //從 NTP 伺服器取得 Unix 時間秒數
//Start UDP Rrequest to NTP Server 91.226.136.136, 82.209.243.241,192.5.41.40
sendData("AT+CIPSTART=\"UDP\",\"91.226.136.136\",123\r\n",5000,DEBUG);
memset(packetBuffer,0,128); //clear buffer
packetBuffer[0]=0xE3; //LI, Version, Mode
packetBuffer[1]=0x00; //Stratum, or type of clock
packetBuffer[2]=0x06; //Polling Interval
packetBuffer[3]=0xEC; //Peer Clock Precision
packetBuffer[12]=0x31; //reference ID (4 bytes)
packetBuffer[13]=0x4E;
packetBuffer[14]=0x31;
packetBuffer[15]=0x34;
//send request to NTP Server
sendData("AT+CIPSEND=48\r\n",1000,DEBUG); //send data length
for (byte i=0; i < 48; i++) {
esp8266.write(packetBuffer[i]);
delay(5);
}
//deal with NTP response
memset(packetBuffer,0,128); //clear buffer to store NTP response
Serial.println();
Serial.println("NTP server answered : ");
int i=0; //packet byte counter
while (esp8266.available() > 0) { //if receive NTP response : fall in loop
byte ch=esp8266.read(); //got NTP response, read one byte for each loop
if (i < 128) {packetBuffer[i]=ch;} //store received byte to packet buffer
//show receving bytes in hex
if (ch < 0x10) {Serial.print('0');} //prefix with '0' if byte value 0~9
Serial.print(ch, HEX);
Serial.print(' ');
if ((((i+1) % 10) == 0)) {Serial.println();} //newline if exceeds 10 bytes
delay(5); //wait 5ms for next incoming byte
i++; //increment packet byte counter
if ((i < 104) && (esp8266.available() == 0)) { //wainting if lags
//Response packets not enough but no response : wait 1.5 seconds
byte wcount=0; //waiting counter
while (esp8266.available() == 0) { //loop until timeout (1.5 seconds)
Serial.print("!"); //show ! means waiting for response packet
delay(100);
wcount += 1; //increment waiting counter
if (wcount >= 15) {break;} //waiting timeout : quit loop
}
}
}
Serial.println();
Serial.println();
Serial.print(i+1);
Serial.println(" bytes received"); // will be more than 48
//Show time stamp (locates from byte 101~104 of the response packet)
Serial.print("NTP time stamp packets (byte 101~104)=");
Serial.print(packetBuffer[101],HEX);
Serial.print(" ");
Serial.print(packetBuffer[102],HEX);
Serial.print(" ");
Serial.print(packetBuffer[103],HEX);
Serial.print(" ");
Serial.print(packetBuffer[104],HEX);
Serial.println();
//handling time packets (4 bytes long) : combine them into words
unsigned long highWord=word(packetBuffer[101],packetBuffer[102]);
unsigned long lowWord=word(packetBuffer[103],packetBuffer[104]);
//shift high word 16 bits left & OR with low word to form a double word
//the result is a NTP time stamp (seconds since Jan 1 1900):
unsigned long secsSince1900=highWord << 16 | lowWord;
Serial.print("NTP time stamp (seconds since 1900-01-01)=");
Serial.println(secsSince1900);
//convert NTP time stamp to Unix time stamp :
//Unix time starts on Jan 1 1970=2208988800 seconds since 1900-01-01
//subtract seventy years to get Unix time stamp, plus 28800 (UTC+8)
unsigned long epoch=secsSince1900 - 2208988800UL;
Serial.print("Unix time stamp (seconds since 1970-01-01)=");
Serial.println(epoch); //print Unix time
sendData("AT+CIPCLOSE\r\n",1000,DEBUG); //close session
return epoch + 28800; //台灣時間為 GMT+8 小時, 即 28800 秒
}
String sendData(String command, const int timeout, boolean debug) {
String response="";
esp8266.print(command); // send the read character to the esp8266
long int time=millis();
while ((time+timeout) > millis()) {
while(esp8266.available()) {
// The esp has data so display its output to the serial window
char c=esp8266.read(); // read the next character.
response += c;
}
}
if (debug) {Serial.print(response);}
return response;
}
123 bytes received
NTP time stamp packets (byte 101~104)=DB 33 44 59
NTP time stamp (seconds since 1900-01-01)=3677570137
Unix time stamp (seconds since 1970-01-01)=1468581337
AT+CIPCLOSE
124 bytes received
NTP time stamp packets (byte 101~104)=DB 33 44 9D
NTP time stamp (seconds since 1900-01-01)=3677570205
Unix time stamp (seconds since 1970-01-01)=1468581405
AT+CIPCLOSE
void setup() {
Serial.begin(9600);
esp8266.begin(9600);
sendData("AT+RST\r\n",2000,DEBUG); // reset ESP8266
sendData("AT+GMR\r\n",1000,DEBUG);
delay(3000); //wait for wifi connection to get local ip
sendData("AT+CIFSR\r\n",1000,DEBUG); //get ip address
Serial.println("Sending request to NTP server ..."); sync_clock(); Alarm.timerRepeat(60, sync_clock); //設定每 60 秒觸發執行 sync_clock()
}
void showDateTime() {
Serial.print(year());
Serial.print("-");
byte M=month();
if (M < 10) {Serial.print('0');}
Serial.print(M);
Serial.print("-");
byte d=day();
if (d < 10) {Serial.print('0');}
Serial.print(d);
Serial.print(" ");
byte h=hour();
if (h < 10) {Serial.print('0');}
Serial.print(h);
Serial.print(":");
byte m=minute();
if (m < 10) {Serial.print('0');}
Serial.print(m);
Serial.print(":");
byte s=second();
if (s < 10) {Serial.print('0');}
Serial.println(s);
}
long getTime() {
//Start UDP Rrequest to NTP Server 91.226.136.136, 82.209.243.241,192.5.41.40
sendData("AT+CIPSTART=\"UDP\",\"91.226.136.136\",123\r\n",5000,DEBUG);
memset(packetBuffer,0,128); //clear buffer
packetBuffer[0]=0xE3; //LI, Version, Mode
packetBuffer[1]=0x00; //Stratum, or type of clock
packetBuffer[2]=0x06; //Polling Interval
packetBuffer[3]=0xEC; //Peer Clock Precision
packetBuffer[12]=0x31; //reference ID (4 bytes)
packetBuffer[13]=0x4E;
packetBuffer[14]=0x31;
packetBuffer[15]=0x34;
//send request to NTP Server
sendData("AT+CIPSEND=48\r\n",1000,DEBUG); //send data length
for (byte i=0; i < 48; i++) {
esp8266.write(packetBuffer[i]);
delay(5);
}
//deal with NTP response
memset(packetBuffer,0,128); //clear buffer to store NTP response
Serial.println();
Serial.println("NTP server answered : ");
int i=0; //packet byte counter
while (esp8266.available() > 0) { //if receive NTP response : fall in loop
byte ch=esp8266.read(); //got NTP response, read one byte for each loop
if (i < 128) {packetBuffer[i]=ch;} //store received byte to packet buffer
//show receving bytes in hex
if (ch < 0x10) {Serial.print('0');} //prefix with '0' if byte value 0~9
Serial.print(ch, HEX);
Serial.print(' ');
if ((((i+1) % 10) == 0)) {Serial.println();} //newline if exceeds 10 bytes
delay(5); //wait 5ms for next incoming byte
i++; //increment packet byte counter
if ((i < 104) && (esp8266.available() == 0)) { //wainting if lags
//Response packets not enough but no response : wait 1.5 seconds
byte wcount=0; //waiting counter
while (esp8266.available() == 0) { //loop until timeout (1.5 seconds)
Serial.print("!"); //show ! means waiting for response packet
delay(100);
wcount += 1; //increment waiting counter
if (wcount >= 15) {break;} //waiting timeout : quit loop
}
}
}
Serial.println();
Serial.println();
Serial.print(i+1);
Serial.println(" bytes received"); // will be more than 48
//Show time stamp (locates from byte 101~104 of the response packet)
Serial.print("NTP time stamp packets (byte 101~104)=");
Serial.print(packetBuffer[101],HEX);
Serial.print(" ");
Serial.print(packetBuffer[102],HEX);
Serial.print(" ");
Serial.print(packetBuffer[103],HEX);
Serial.print(" ");
Serial.print(packetBuffer[104],HEX);
Serial.println();
//handling time packets (4 bytes long) : combine them into words
unsigned long highWord=word(packetBuffer[101],packetBuffer[102]);
unsigned long lowWord=word(packetBuffer[103],packetBuffer[104]);
//shift high word 16 bits left & OR with low word to form a double word
//the result is a NTP time stamp (seconds since Jan 1 1900):
unsigned long secsSince1900=highWord << 16 | lowWord;
Serial.print("NTP time stamp (seconds since 1900-01-01)=");
Serial.println(secsSince1900);
//convert NTP time stamp to Unix time stamp :
//Unix time starts on Jan 1 1970=2208988800 seconds since 1900-01-01
//subtract seventy years to get Unix time stamp, plus 28800 (UTC+8)
unsigned long epoch=secsSince1900 - 2208988800UL;
Serial.print("Unix time stamp (seconds since 1970-01-01)=");
Serial.println(epoch); //print Unix time
sendData("AT+CIPCLOSE\r\n",1000,DEBUG); //close session
return epoch + 28800;
}
String sendData(String command, const int timeout, boolean debug) {
String response="";
esp8266.print(command); // send the read character to the esp8266
long int time=millis();
while ((time+timeout) > millis()) {
while(esp8266.available()) {
// The esp has data so display its output to the serial window
char c=esp8266.read(); // read the next character.
response += c;
}
}
if (debug) {Serial.print(response);}
return response;
}
void setup() {
Serial.begin(9600);
esp8266.begin(9600);
sendData("AT+RST\r\n",2000,DEBUG); // reset ESP8266
sendData("AT+GMR\r\n",1000,DEBUG);
delay(3000); //wait for wifi connection to get local ip
sendData("AT+CIFSR\r\n",1000,DEBUG); //get ip address
Serial.println("Sending request to NTP server ...");
sync_clock();
Alarm.timerRepeat(60, sync_clock);
}
String getDateTime() { //傳回日期時間
String dt=(String)year() + "-";
byte M=month();
if (M < 10) {dt.concat('0');}
dt.concat(M);
dt.concat('-');
byte d=day();
if (d < 10) {dt.concat('0');}
dt.concat(d);
dt.concat(' ');
byte h=hour();
if (h < 10) {dt.concat('0');}
dt.concat(h);
dt.concat(':');
byte m=minute();
if (m < 10) {dt.concat('0');}
dt.concat(m);
dt.concat(':');
byte s=second();
if (s < 10) {dt.concat('0');}
dt.concat(s); return dt; //傳回格式如 2016-07-16 16:09:23 的日期時間字串
}
long getTime() {
//Start UDP Rrequest to NTP Server 91.226.136.136, 82.209.243.241,192.5.41.40
sendData("AT+CIPSTART=\"UDP\",\"91.226.136.136\",123\r\n",5000,DEBUG);
memset(packetBuffer,0,128); //clear buffer
packetBuffer[0]=0xE3; //LI, Version, Mode
packetBuffer[1]=0x00; //Stratum, or type of clock
packetBuffer[2]=0x06; //Polling Interval
packetBuffer[3]=0xEC; //Peer Clock Precision
packetBuffer[12]=0x31; //reference ID (4 bytes)
packetBuffer[13]=0x4E;
packetBuffer[14]=0x31;
packetBuffer[15]=0x34;
//send request to NTP Server
sendData("AT+CIPSEND=48\r\n",1000,DEBUG); //send data length
for (byte i=0; i < 48; i++) {
esp8266.write(packetBuffer[i]);
delay(5);
}
//deal with NTP response
memset(packetBuffer,0,128); //clear buffer to store NTP response
Serial.println();
Serial.println("NTP server answered : ");
int i=0; //packet byte counter
while (esp8266.available() > 0) { //if receive NTP response : fall in loop
byte ch=esp8266.read(); //got NTP response, read one byte for each loop
if (i < 128) {packetBuffer[i]=ch;} //store received byte to packet buffer
//show receving bytes in hex
if (ch < 0x10) {Serial.print('0');} //prefix with '0' if byte value 0~9
Serial.print(ch, HEX);
Serial.print(' ');
if ((((i+1) % 10) == 0)) {Serial.println();} //newline if exceeds 10 bytes
delay(5); //wait 5ms for next incoming byte
i++; //increment packet byte counter
if ((i < 104) && (esp8266.available() == 0)) { //wainting if lags
//Response packets not enough but no response : wait 1.5 seconds
byte wcount=0; //waiting counter
while (esp8266.available() == 0) { //loop until timeout (1.5 seconds)
Serial.print("!"); //show ! means waiting for response packet
delay(100);
wcount += 1; //increment waiting counter
if (wcount >= 15) {break;} //waiting timeout : quit loop
}
}
}
Serial.println();
Serial.println();
Serial.print(i+1);
Serial.println(" bytes received"); // will be more than 48
//Show time stamp (locates from byte 101~104 of the response packet)
Serial.print("NTP time stamp packets (byte 101~104)=");
Serial.print(packetBuffer[101],HEX);
Serial.print(" ");
Serial.print(packetBuffer[102],HEX);
Serial.print(" ");
Serial.print(packetBuffer[103],HEX);
Serial.print(" ");
Serial.print(packetBuffer[104],HEX);
Serial.println();
//handling time packets (4 bytes long) : combine them into words
unsigned long highWord=word(packetBuffer[101],packetBuffer[102]);
unsigned long lowWord=word(packetBuffer[103],packetBuffer[104]);
//shift high word 16 bits left & OR with low word to form a double word
//the result is a NTP time stamp (seconds since Jan 1 1900):
unsigned long secsSince1900=highWord << 16 | lowWord;
Serial.print("NTP time stamp (seconds since 1900-01-01)=");
Serial.println(secsSince1900);
//convert NTP time stamp to Unix time stamp :
//Unix time starts on Jan 1 1970=2208988800 seconds since 1900-01-01
//subtract seventy years to get Unix time stamp, plus 28800 (UTC+8)
unsigned long epoch=secsSince1900 - 2208988800UL;
Serial.print("Unix time stamp (seconds since 1970-01-01)=");
Serial.println(epoch); //print Unix time
sendData("AT+CIPCLOSE\r\n",1000,DEBUG); //close session
return epoch + 28800;
}
String sendData(String command, const int timeout, boolean debug) {
String response="";
esp8266.print(command); // send the read character to the esp8266
long int time=millis();
while ((time+timeout) > millis()) {
while(esp8266.available()) {
// The esp has data so display its output to the serial window
char c=esp8266.read(); // read the next character.
response += c;
}
}
if (debug) {Serial.print(response);}
return response;
}
void setup() {
Serial.begin(9600);
esp8266.begin(9600);
sendData("AT+RST\r\n",2000,DEBUG); // reset ESP8266
sendData("AT+GMR\r\n",1000,DEBUG);
delay(3000); //wait for wifi connection to get local ip
sendData("AT+CIFSR\r\n",1000,DEBUG); //get ip address
Serial.println("Sending request to NTP server ...");
sync_clock();
Alarm.timerRepeat(60, sync_clock); lcd.begin(16,2); //define 2*16 LCD lcd.clear(); //clear screen
}
void loop() {
String dt=getDateTime();
Serial.println(dt); String d=dt.substring(0,dt.indexOf(" ")); //以空格拆分日期與時間 String t=dt.substring(dt.indexOf(" ") + 1); //空格後為時間 lcd.setCursor(0,0); //move to (x,y) lcd.print(d); //print date lcd.setCursor(0,1); //move to (x,y) lcd.print(t); //print time
Alarm.delay(1000);
}
void sync_clock() {
setTime(getTime());
}
String getDateTime() {
String dt=(String)year() + "-";
byte M=month();
if (M < 10) {dt.concat('0');}
dt.concat(M);
dt.concat('-');
byte d=day();
if (d < 10) {dt.concat('0');}
dt.concat(d);
dt.concat(' ');
byte h=hour();
if (h < 10) {dt.concat('0');}
dt.concat(h);
dt.concat(':');
byte m=minute();
if (m < 10) {dt.concat('0');}
dt.concat(m);
dt.concat(':');
byte s=second();
if (s < 10) {dt.concat('0');}
dt.concat(s);
return dt;
}
long getTime() {
//Start UDP Rrequest to NTP Server 91.226.136.136, 82.209.243.241,192.5.41.40
sendData("AT+CIPSTART=\"UDP\",\"91.226.136.136\",123\r\n",5000,DEBUG);
memset(packetBuffer,0,128); //clear buffer
packetBuffer[0]=0xE3; //LI, Version, Mode
packetBuffer[1]=0x00; //Stratum, or type of clock
packetBuffer[2]=0x06; //Polling Interval
packetBuffer[3]=0xEC; //Peer Clock Precision
packetBuffer[12]=0x31; //reference ID (4 bytes)
packetBuffer[13]=0x4E;
packetBuffer[14]=0x31;
packetBuffer[15]=0x34;
//send request to NTP Server
sendData("AT+CIPSEND=48\r\n",1000,DEBUG); //send data length
for (byte i=0; i < 48; i++) {
esp8266.write(packetBuffer[i]);
delay(5);
}
//deal with NTP response
memset(packetBuffer,0,128); //clear buffer to store NTP response
Serial.println();
Serial.println("NTP server answered : ");
int i=0; //packet byte counter
while (esp8266.available() > 0) { //if receive NTP response : fall in loop
byte ch=esp8266.read(); //got NTP response, read one byte for each loop
if (i < 128) {packetBuffer[i]=ch;} //store received byte to packet buffer
//show receving bytes in hex
if (ch < 0x10) {Serial.print('0');} //prefix with '0' if byte value 0~9
Serial.print(ch, HEX);
Serial.print(' ');
if ((((i+1) % 10) == 0)) {Serial.println();} //newline if exceeds 10 bytes
delay(5); //wait 5ms for next incoming byte
i++; //increment packet byte counter
if ((i < 104) && (esp8266.available() == 0)) { //wainting if lags
//Response packets not enough but no response : wait 1.5 seconds
byte wcount=0; //waiting counter
while (esp8266.available() == 0) { //loop until timeout (1.5 seconds)
Serial.print("!"); //show ! means waiting for response packet
delay(100);
wcount += 1; //increment waiting counter
if (wcount >= 15) {break;} //waiting timeout : quit loop
}
}
}
Serial.println();
Serial.println();
Serial.print(i+1);
Serial.println(" bytes received"); // will be more than 48
//Show time stamp (locates from byte 101~104 of the response packet)
Serial.print("NTP time stamp packets (byte 101~104)=");
Serial.print(packetBuffer[101],HEX);
Serial.print(" ");
Serial.print(packetBuffer[102],HEX);
Serial.print(" ");
Serial.print(packetBuffer[103],HEX);
Serial.print(" ");
Serial.print(packetBuffer[104],HEX);
Serial.println();
//handling time packets (4 bytes long) : combine them into words
unsigned long highWord=word(packetBuffer[101],packetBuffer[102]);
unsigned long lowWord=word(packetBuffer[103],packetBuffer[104]);
//shift high word 16 bits left & OR with low word to form a double word
//the result is a NTP time stamp (seconds since Jan 1 1900):
unsigned long secsSince1900=highWord << 16 | lowWord;
Serial.print("NTP time stamp (seconds since 1900-01-01)=");
Serial.println(secsSince1900);
//convert NTP time stamp to Unix time stamp :
//Unix time starts on Jan 1 1970=2208988800 seconds since 1900-01-01
//subtract seventy years to get Unix time stamp, plus 28800 (UTC+8)
unsigned long epoch=secsSince1900 - 2208988800UL;
Serial.print("Unix time stamp (seconds since 1970-01-01)=");
Serial.println(epoch); //print Unix time
sendData("AT+CIPCLOSE\r\n",1000,DEBUG); //close session
return epoch + 28800;
}
String sendData(String command, const int timeout, boolean debug) {
String response="";
esp8266.print(command); // send the read character to the esp8266
long int time=millis();
while ((time+timeout) > millis()) {
while(esp8266.available()) {
// The esp has data so display its output to the serial window
char c=esp8266.read(); // read the next character.
response += c;
}
}
if (debug) {Serial.print(response);}
return response;
}