Skip to content

Instantly share code, notes, and snippets.

@wouterds
Created January 6, 2019 14:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wouterds/40e4d75347fb9881a1dd9c4f69e2b8e2 to your computer and use it in GitHub Desktop.
Save wouterds/40e4d75347fb9881a1dd9c4f69e2b8e2 to your computer and use it in GitHub Desktop.
#include <Wire.h>
#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>
#define LED D1
const char *ssid = "Wouter's Place";
const char *password = "";
ESP8266WebServer server(80);
const char HTML[] PROGMEM = R"=====(
<!DOCTYPE html>
<html>
<body>
<h1>Hello World</h1>
<button onclick="(function () { var xmlreq = new XMLHttpRequest(); xmlreq.open('GET', '/led-on'); xmlreq.send(); })()">On!</button>
<button onclick="(function () { var xmlreq = new XMLHttpRequest(); xmlreq.open('GET', '/led-off'); xmlreq.send(); })()">Off!</button>
</body>
</html>
)=====";
void handleRoot() {
Serial.println("handleRoot");
digitalWrite(LED_BUILTIN, LOW);
String response = HTML;
server.send(200, "text/html", response);
digitalWrite(LED_BUILTIN, HIGH);
}
void handleLedOn() {
Serial.println("handleLedOn");
digitalWrite(LED, HIGH);
server.send(204);
}
void handleLedOff() {
Serial.println("handleLedOff");
digitalWrite(LED, LOW);
server.send(204);
}
void setup(void)
{
Serial.begin(9600);
Serial.println();
pinMode(LED_BUILTIN, OUTPUT);
pinMode(LED, OUTPUT);
Serial.print("Connecting to: ");
Serial.println(ssid);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED)
{
delay(250);
Serial.print(".");
}
Serial.println();
Serial.print("Connected to wifi, ip: ");
Serial.println(WiFi.localIP());
Serial.println("Starting server..");
server.on("/", handleRoot);
server.on("/led-on", handleLedOn);
server.on("/led-off", handleLedOff);
server.begin();
Serial.println("Web server running!");
}
void loop()
{
server.handleClient();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment