Created
September 6, 2017 13:30
-
-
Save Antoinebr/59c6d7abec8ce1ce99dfb48d24af0974 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <ESP8266WiFi.h> | |
#include <WiFiClient.h> | |
#include <ESP8266WebServer.h> | |
#include <ESP8266mDNS.h> | |
const char* ssid = "myWifiSSID"; | |
const char* password = "myWifiPassWord"; | |
ESP8266WebServer server(80); | |
void handleRoot() { | |
server.send(200, "text/plain", "hello from esp8266!"); | |
} | |
void handleNotFound(){ | |
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); | |
} | |
void setup(void){ | |
Serial.begin(115200); | |
WiFi.begin(ssid, password); | |
Serial.println(""); | |
// Wait for connection | |
startWIFI(); | |
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){ | |
//connect wifi if not connected | |
if (WiFi.status() != WL_CONNECTED) { | |
delay(1); | |
startWIFI(); | |
return; | |
} | |
server.handleClient(); | |
} | |
void startWIFI(void) { | |
// Connect to WiFi network | |
Serial.println(); | |
delay(10); | |
Serial.println(); | |
delay(10); | |
Serial.print("Connecting to "); | |
delay(10); | |
Serial.println(ssid); | |
delay(10); | |
WiFi.begin(ssid, password); | |
while (WiFi.status() != WL_CONNECTED) { | |
Serial.print("."); | |
delay(500); | |
} | |
Serial.println(""); | |
Serial.println("WiFi connected"); | |
// Start the server | |
server.begin(); | |
Serial.println("Server started"); | |
// Print the IP address | |
Serial.print("ESP8266 IP: "); | |
Serial.println(WiFi.localIP()); | |
// Print the server port | |
delay(300); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment