|
#include <Arduino.h> |
|
#include <ESP8266WiFi.h> |
|
#include <WiFiClient.h> |
|
#include <ESP8266WiFiMulti.h> |
|
#include <ESP8266mDNS.h> |
|
#include <ESP8266WebServer.h> |
|
|
|
ESP8266WiFiMulti wifiMulti; // Create an instance of the ESP8266WiFiMulti class, called 'wifiMulti' |
|
|
|
ESP8266WebServer server(80); // Create a webserver object that listens for HTTP request on port 80 |
|
|
|
int RED = D5; |
|
int GREEN = D6; |
|
|
|
void handleRoot(); |
|
void handleLED(); |
|
void handleNotFound(); |
|
|
|
void setup(void){ |
|
Serial.begin(115200); |
|
delay(10); |
|
Serial.println('\n'); |
|
|
|
pinMode(RED, OUTPUT); // Make RED pin D5 an output pin |
|
pinMode(GREEN, OUTPUT); // Make GREEN pin D6 an output pin |
|
|
|
digitalWrite(GREEN, true); |
|
|
|
wifiMulti.addAP("SSID", "PASSWORD"); // add Wi-Fi networks you want to connect to |
|
|
|
Serial.println("Connecting ..."); |
|
while (wifiMulti.run() != WL_CONNECTED) { // Wait for the Wi-Fi to connect: scan for Wi-Fi networks, and connect to the strongest of the networks above |
|
delay(250); |
|
Serial.print('.'); |
|
} |
|
Serial.println('\n'); |
|
Serial.print("Connected to "); |
|
Serial.println(WiFi.SSID()); |
|
Serial.print("IP address:\t"); |
|
Serial.println(WiFi.localIP()); |
|
|
|
if (MDNS.begin("esp8266")) { |
|
Serial.println("mDNS responder started"); |
|
} else { |
|
Serial.println("Error setting up MDNS responder!"); |
|
} |
|
|
|
server.on("/", HTTP_GET, handleRoot); // Call the 'handleRoot' function when a client requests URI "/" |
|
server.on("/LED", HTTP_POST, handleLED); // Call the 'handleLED' function when a POST request is made to URI "/LED" |
|
server.onNotFound(handleNotFound); |
|
|
|
server.begin(); |
|
Serial.println("HTTP server started"); |
|
} |
|
|
|
void loop(void){ |
|
server.handleClient(); |
|
} |
|
|
|
void handleRoot() { |
|
server.send(200, "text/html", "<form action=\"/LED\" method=\"POST\"><input type=\"submit\" name='color' value=\"red\"><input type=\"submit\" name='color' value=\"green\"></form>"); |
|
} |
|
|
|
void handleLED() { |
|
String color = server.arg(0); |
|
String red = "red"; |
|
|
|
if (color == red) { |
|
digitalWrite(GREEN, false); |
|
digitalWrite(RED, true); |
|
} else { |
|
digitalWrite(RED, false); |
|
digitalWrite(GREEN, true); |
|
} |
|
server.sendHeader("Location","/"); |
|
server.send(303); |
|
} |
|
|
|
void handleNotFound(){ |
|
server.send(404, "text/plain", "404: Not found"); // Send HTTP status 404 (Not Found) when there's no handler for the URI in the request |
|
} |