#include <SoftwareSerial.h>
#define _baudrate 9600
#define _rxpin 4
#define _txpin 5
#include "Timer.h"
Timer t;
SoftwareSerial debug( _rxpin, _txpin ); // RX, TX
//*-- IoT Information
#define SSID "Huang"
#define PASS "e53asus0211"
#define IP "184.106.153.149" // ThingSpeak IP Address: 184.106.153.149
// 使用 GET 傳送資料的格式
// GET /update?key=[THINGSPEAK_KEY]&field1=[data 1]&filed2=[data 2]...;
String GET = "GET /update?key=MIN085MR4XATH8VD";
void setup() {
Serial.begin( _baudrate );
debug.begin( _baudrate );
t.every(100, Wifi_main);
}
void loop() {
t.update();
}
int Wifi_State,delaytime,ErrorCount,W=12,D=34;
String cmd;
void Wifi_main(){
switch (Wifi_State) {
case 0: //-----------------------------------------------initial sent AT test
sendDebug("AT");
Wifi_State=1;
break;
case 1:
if (delaytime==10){ //delay 1 sec
delaytime=0;
if(debug.find("OK")){ //test success
Serial.println("RECEIVED: OK\nData ready to sent!");
Wifi_State=2; //next setting wifi mode
}
else{ //test fail
Serial.println("NO RESEPONCE!");
Wifi_State=7; //go back reset delay
}
}
else{delaytime++;}
break;
case 2://-----------------------------------------------setting wifi mode
debug.println("AT+CWMODE=1");
Wifi_State=3; //next setting wifi mode
break;
case 3:
if (delaytime==20){ //delay 2 sec
delaytime=0;
cmd="AT+CWJAP=\"";
cmd+=SSID;
cmd+="\",\"";
cmd+=PASS;
cmd+="\"";
sendDebug(cmd);
Wifi_State=4; //next check wifi respones after delay 5 sec
}
else{delaytime++;}
break;
case 4:
if (delaytime==50){ //delay 5 sec
delaytime=0;
if(debug.find("OK")){
Serial.println("RECEIVED: OK");
Wifi_State=5; //next sent data to the clould
}
else{
Serial.println("RECEIVED: Error");
Wifi_State=2; //back
}
}
else{delaytime++;}
break;
case 5: //-----------------------------------------------sent data to the clould
// 設定 ESP8266 作為 Client 端
cmd = "AT+CIPSTART=\"TCP\",\"";
cmd += IP;
cmd += "\",80";
sendDebug(cmd);
if(debug.find("Error" )){Serial.print( "RECEIVED: Error\nExit1" );}
cmd = GET + "&field1=" + String(W) + "&field2=" + String(D) +"\r\n";
debug.print( "AT+CIPSEND=" );
debug.println( cmd.length() );
if(debug.find( ">" ) ){
Serial.print(">");
Serial.print(cmd);
debug.print(cmd);
}
else{debug.print( "AT+CIPCLOSE" );}
if( debug.find("OK") ){
Serial.println( "RECEIVED: OK" );
Wifi_State=6; //next go space and wait
}
else{
Serial.println( "RECEIVED: Error" );
if (ErrorCount==5){
ErrorCount=0;
Wifi_State=7; //there was something wrong must be go back reset.
}
else{
Wifi_State=6; //restart
ErrorCount++;
}
}
break;
case 6: //-----------------------------------------------end sent
if (delaytime==50){ //delay 5 sec
delaytime=0;
Wifi_State=5; //back
}
else{delaytime++;}
break;
case 7 : //-----------------------------------------------go back reset delay
if (delaytime==50){ //delay 5 sec
delaytime=0;
Wifi_State=0; //back
}
else{delaytime++;}
break;
}
}
void sendDebug(String sent_cmd)
{
Serial.print("SEND: ");
Serial.println(sent_cmd);
debug.println(sent_cmd);
}
全站熱搜