堕落不振功业废,勤耕不辍日月新

esp8266 wifi控制代码(好)

综合 hailen 4℃

#include <ESP8266WiFi.h>
#include <ArduinoJson.h>

const char* ssid = “***”; //修改成你可访问的wifi名称
const char* password = “***”; // 修改成wifi密码

const char* host = “192.168.1.10”; // 你的网点域名或IP
String path = “/wifiarduino/light.json”; // 文件路径
const int pin = 2;
void setup() {
pinMode(pin, OUTPUT);
pinMode(pin, HIGH);
Serial.begin(115200);
delay(10);
Serial.print(“Connecting to “);
Serial.println(ssid);
WiFi.begin(ssid, password);
int wifi_ctr = 0;
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(“.”);
}
Serial.println(“WiFi connected”);
Serial.println(“IP address: ” + WiFi.localIP());
}
void loop() {
Serial.print(“connecting to “);
Serial.println(host);
WiFiClient client;
const int httpPort = 80;
if (!client.connect(host, httpPort)) {
Serial.println(“connection failed”);
return;
}
client.print(String(“GET “) + path + ” HTTP/1.1
” + “Host: ” + host + ”
” + “Connection: keep-alive

“);
delay(500); // wait for server to respond
// read response
String section=”header”;
while(client.available()){
String line = client.readStringUntil(‘
‘);
// Serial.print(line); // we’ll parse the HTML body here
if (section==”header”) { // headers..
Serial.print(“.”);
if (line==”
“) { // skips the empty space at the beginning
section=”json”;
}
}
else if (section==”json”) { // print the good stuff
section=”ignore”;
String result = line.substring(1); // Parse JSON
int size = result.length() + 1;
char json[size];
result.toCharArray(json, size);
StaticJsonBuffer<200> jsonBuffer;
JsonObject& json_parsed = jsonBuffer.parseObject(json);
if (!json_parsed.success())
{
Serial.println(“parseObject() failed”);
return;
}
// Make the decision to turn off or on the LED
if (strcmp(json_parsed[“light”], “on”) == 0) {
digitalWrite(pin, HIGH);
Serial.println(“LED ON”);
}
else {
digitalWrite(pin, LOW);
Serial.println(“led off”);
}
}
}
Serial.print(“closing connection. “);
}

转载请注明:我是IT » esp8266 wifi控制代码(好)

喜欢 (0)or分享 (0)