可以通过浏览器控制开关灯http://192.168.1.120/gpio/1,得到反馈GPIO is now on,再试一种webserver结构就结束这一节了。
ESP8266WebServer server(80);
const int led = 12;
void handleRoot() {
digitalWrite(led, 0);
server.send(200, "text/plain", "hello from esp8266!");
digitalWrite(led, 1);
}
void handleNotFound(){
digitalWrite(led, 0);
String message = "File Not Found\n\n";
message += "URI: ";
message += server.uri();
message += "\nMethod: ";
message += (server.method() == HTTP_GET)?"GET":"POST";
message += "\nArguments: ";
message += server.args();
message += "\n";
for (uint8_t i=0; i<server.args(); i++){
message += " " + server.argName(i) + ": " + server.arg(i) + "\n";
}
server.send(404, "text/plain", message);
digitalWrite(led, 1);
}
void setup(void){
pinMode(led, OUTPUT);
digitalWrite(led, 1);
Serial.begin(115200);
WiFi.begin(ssid, password);
Serial.println("");
// Wait for connection
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.print("Connected to ");
Serial.println(ssid);
Serial.print("IP address: ");
Serial.println(WiFi.localIP());
if (MDNS.begin("esp8266")) {
Serial.println("MDNS responder started");
}
server.on("/", handleRoot);
server.on("/inline", [](){
server.send(200, "text/plain", "this works as well");
});
server.onNotFound(handleNotFound);
server.begin();
Serial.println("HTTP server started");
}
void loop(void){
server.handleClient();
}