這是一個對ESP8266 WIFI模組的測試,ESP8266是一個價格便宜的WIFI模組,
而且是Mega2560用UART即可傳輸資料到ESP8266,相當方便,
首先,要使用ESP8266前要對其指令先有了解,然後是到thingspeak.com註冊,thingspeak.com提供8 channels的資料上傳,
幸運的是,我們可以不必從零開始,有依些範例是前人寫好,我們可以參考:
1. thingspeak.com註冊可以參考: http://www.instructables.com/id/ESP8266-Wifi-Temperature-Logger/?ALLSTEPS
2. ESP8266的接線可以參考:http://electronut.in/an-iot-project-with-esp8266/
以下是我寫的Arduino code:
#include <SoftwareSerial.h>
//define ESP8266
#define MYID "PowerNet" //[YOUR_SSID]
#define PASS "12345678" //[YOUR_PASSWORD]
#define IP "184.106.153.149" // thingspeak.com
String GET = "GET /update?key=CTSJW3KYC9QFDXSZ&field1="; //[THINGSPEAK_KEY]
//define HC-SR501
int IRpin = 4;
String IRF;
SoftwareSerial wifi(12, 13); // RX, TX
void setup()
{
pinMode(IRpin, INPUT);
wifi.begin(9600);
Serial.begin(9600);
//sendDebug("AT");
// reset ESP8266
sendDebug("AT+RST");
delay(5000);
if(wifi.find("OK")){
Serial.println("RECEIVED: OK");
connectWiFi();
}
else {
Serial.println("RECEIVED: Error");
}
connectWiFi();
}
void loop(){
char IR = digitalRead(IRpin);
if (IR) {
IRF = "1";
}
else {
IRF = "0";
}
Serial.println("IRF = "+IRF);
//Serial.println(IRF);
updateStatus(IRF);
delay(16000); // thingspeak needs 15 sec delay between updates
}
void sendDebug(String cmd){
Serial.print("SEND: ");
Serial.println(cmd);
wifi.println(cmd);
}
void updateStatus(String IRF){
String cmd = "AT+CIPSTART=\"TCP\",\"";
cmd += IP;
cmd += "\",80";
wifi.println(cmd);
Serial.println(cmd);
delay(2000);
if(wifi.find("Error")){
Serial.println("AT+CIPSTART error");
return;
}
cmd = GET;
cmd += IRF;
cmd += "\r\n";
Serial.println(cmd);
wifi.print("AT+CIPSEND=");
wifi.println(cmd.length());
if(wifi.find(">")){
Serial.print(">");
Serial.print(cmd);
wifi.print(cmd);
}
else{
wifi.println("AT+CIPCLOSE");
Serial.println("AT+CIPCLOSE");
}
if(wifi.find("OK")){
Serial.println("RECEIVED: Update OK");
}
else{
Serial.println("RECEIVED: Update Error");
}
}
boolean connectWiFi(){
wifi.println("AT+CWMODE=1");
delay(2000);
String cmd="AT+CWJAP=\"";
cmd+=MYID;
cmd+="\",\"";
cmd+=PASS;
cmd+="\"";
wifi.println(cmd);
Serial.println(cmd);
delay(5000);
if(wifi.find("OK")){
Serial.println("Connnection RECEIVED: OK");
return true;
}else{
Serial.println("Connection RECEIVED: Error");
return false;
}
}
以及用COM monitor觀察程式的重要步驟是否都正確執行,程式碼中有Serial.println中的輸出項內容都是偵錯功能,
將人體紅外線感測器HC-SR501的資料傳到Thingspeak.com,
最後是系統的配置圖,
留言列表