5. 傳送資料出去
此段程式碼可以利用ESP8266 Wifi模組,將訊號傳至另一個裝置
接收裝置可以參考 Part 1.3 的程式碼稍作修改
亦可向ThingSpeak等物聯網網站傳送數據做長期記錄 (前提是你的AP穩定性要夠高)
#include <SoftwareSerial.h>
#define TX 3 //ESP8266 TX接3
#define RX 2 //ESP8266 RX接2
#define SSID " " //這裡填入你家AP的SSID
#define PASSWORD " " //這裡填入你家AP的密碼
#define Rec "192.168.0.106" //這裡填入你要連線的目標IP
SoftwareSerial esp8266(TX,RX);
#define DEBUG true
void setup() {
Serial.begin(9600); //start hardware serial port
esp8266.begin(9600); //start soft serial port
pinMode(13,OUTPUT); //連線指示燈
String cmd="AT+CWJAP=\"";
cmd+=SSID;
cmd+="\",\"";
cmd+=PASSWORD;
cmd+="\"";
cmd+="\r\n";
sendData("AT+RST\r\n",2000,DEBUG); //重啟ESP8266
sendData("AT+CWMODE=1\r\n",100,DEBUG); // 設定為STA模式
sendData(cmd,10000,DEBUG); // 取得連線(視AP連線效能作調整,預設7000毫秒)
sendData("AT+CIFSR\r\n",100,DEBUG); // 獲得IP
sendData("AT+CIPMUX=1\r\n",100,DEBUG); // 開啟多除連接模式
sendData("AT+CIPSERVER=1,8080\r\n",100,DEBUG); // 設定連接埠為8080
}
void loop() {
digitalWrite(13,1); //當ESP8266 連上AP,自動亮燈
String cipStart="AT+CIPSTART=0,\"TCP\",\"";
cipStart += Rec;
cipStart += "\",8080";
cipStart +="\r\n";
sendData(cipStart,10000,DEBUG); //延遲時間800毫秒可以自行調整
String Command = "/?X=A"; //這裡填入你要傳送的指令或數據
String cipSend = "AT+CIPSEND=0,";
cipSend +=Command.length();
cipSend +="\r\n";
sendData(cipSend,200,DEBUG);
sendData(Command,10000,DEBUG);
delay(5000);
}
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();
do{
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(response.charAt(response.length()-2)=='O'&&response.charAt(response.length()-1)=='K'){
time=0;
}
}while ((time+timeout) > millis());
if (debug) {Serial.print(response);}
return response;
}