【醬菜創客】ESP8266連線伺服器實現遠端控制LED燈
阿新 • • 發佈:2019-01-24
#include <ESP8266WiFi.h> WiFiClient client; #define relay1 2 //繼電器連線在8266的GPIO2上 const char *ssid = "xxxx";//這裡是我的wifi,你使用時修改為你要連線的wifi ssid const char *password = "xxxxxxxxxxx";//你要連線的wifi密碼 const char *host = "www.jcckiot.com";//醬菜創客伺服器IP const int httpPort =8266;//埠號 String line =""; int m=0; void setup() { Serial.begin(115200); delay(10); pinMode(relay1,OUTPUT); // We start by connecting to a WiFi network Serial.println(); Serial.println(); Serial.print("Connecting to "); Serial.println(ssid); WiFi.begin(ssid, password); while (WiFi.status() != WL_CONNECTED) { delay(500); Serial.print("."); } Serial.println(""); Serial.println("WiFi connected"); Serial.println("IP address: "); Serial.println(WiFi.localIP()); while (!client.connect(host, httpPort)) { Serial.println("connection failed"); //return; delay(500); } Serial.print("connecting to "); Serial.println(host); client.write("mode=bind&apikey=你的apikey&data={ck001000bind}\r\n");//繫結apikey,修改成你自己的apikey delay(10); } //int value = 0; void loop() { while(client.available()){ String line = client.readStringUntil('\r'); Serial.println(line); //valueread=line[47]; //Serial.println(valueread); if(line[5]=='3' & line[8]=='0' & line[9]=='1') { digitalWrite(relay1,HIGH); Serial.println("led on"); } if(line[5]=='3' & line[8]=='0' & line[9]=='0') { digitalWrite(relay1,LOW); Serial.println("led off"); } } String line =""; m++; if(m%40==0) { client.write("mode=up&apikey=你的apikey&data={ck003000life}\r\n");//傳送心跳訊息,修改成你自己的apikey m=0; } delay(500); }