// HTTP server that offers HTTP clients (e.g. browser) to control an LED. // Based on below page, but modified for educational purposes: // http://www.instructables.com/id/Quick-Start-to-Nodemcu-ESP8266-on-Arduino-IDE/ #include // WiFi credentials and server object const char* WIFI_SSID = ""; const char* WIFI_PWD = ""; WiFiServer server(80); // create a server connected to TCP port 80 // String buffer in which the HTTP response is compiled const int RESPONSE_SIZE = 1024; String response; // simplify handling of builtin LED; note that it is inverted w/ regards to HIGH/LOW void ledInit() { pinMode(LED_BUILTIN, OUTPUT); } boolean ledIsOn() { return (digitalRead(LED_BUILTIN) == LOW); } void ledOff() { digitalWrite(LED_BUILTIN, HIGH); } void ledOn() { digitalWrite(LED_BUILTIN, LOW); } void ledFlip() { ledIsOn() ? ledOff() : ledOn(); } // main application logic in setup() and loop() void setup() { ledInit(); Serial.begin(115200); response.reserve(RESPONSE_SIZE); // connect to WiFi Serial.println(); Serial.println(); Serial.print("Connecting to "); Serial.print(WIFI_SSID); WiFi.begin(WIFI_SSID, WIFI_PWD); while (WiFi.status() != WL_CONNECTED) { Serial.print("."); ledFlip(); // flash LED while connecting delay(250); } Serial.println(" connected"); // server starts listening for incoming connections server.begin(); Serial.print("Server started. Connect via URL http://"); Serial.print(WiFi.localIP()); Serial.println("/"); } void loop() { // check if "client" connected to the server WiFiClient client = server.available(); if (client) { if (client.connected()) { Serial.println(""); Serial.println("Client connected"); // wait until client sends data or disconnects while (!client.available()) { if (!client.connected()) { client.stop(); return; } } // read first line of the request, discard the rest const String request = client.readStringUntil('\r'); client.flush(); Serial.println(request); // act on content of first request line if (request.indexOf("/favicon.ico") != -1) { // return HTTP Not Found response (most browsers add a request for /favicon.ico) response = "HTTP/1.1 404 Not Found\r\n"; Serial.print(response); client.println(response); } else { // set LED on/off as requested if (request.indexOf("/LED=ON") != -1) {ledOn();} if (request.indexOf("/LED=OFF") != -1) {ledOff();} if (request.indexOf("/LED=TOGGLE") != -1) {ledFlip();} // return HTTP OK response response = "HTTP/1.1 200 OK\r\n"; Serial.print(response); response.concat("Content-Type: text/html\r\n" "\r\n" "\r\n" "\r\n" "ESP8266 LED server\r\n" "\r\n" "LED is "); response.concat(ledIsOn() ? "ON" : "OFF"); response.concat("

\r\n" " " " " "\r\n" "\r\n" "\r\n"); client.println(response); } Serial.println("Server disconnects"); } // close the connection from server-side client.stop(); } }