Skip to content

Instantly share code, notes, and snippets.

@madpilot
Last active June 7, 2022 15:51
Show Gist options
  • Save madpilot/2c36d32526cf386889b75d883486ee69 to your computer and use it in GitHub Desktop.
Save madpilot/2c36d32526cf386889b75d883486ee69 to your computer and use it in GitHub Desktop.
#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>
#include <ESP8266mDNS.h>
const char* ssid = "........";
const char* password = "........";
ESP8266WebServer server(80);
#define ON_STATE 1
#define OFF_STATE 0
#define LED 4
#define RELAY 5
#define BUTTON 13
int switchState = OFF_STATE;
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 switchOn();
void switchOff();
void toggleSwitch();
int getSwitchState() {
return switchState;
}
void setSwitchState(int state) {
switchState = state;
}
void switchOn() {
digitalWrite(RELAY, ON_STATE);
setSwitchState(ON_STATE);
}
void switchOff() {
digitalWrite(RELAY, OFF_STATE);
setSwitchState(OFF_STATE);
}
void switchToggle() {
if(getSwitchState() == ON_STATE) {
switchOff();
} else {
switchOn();
}
}
void setup() {
Serial.begin(115200);
pinMode(LED, OUTPUT);
pinMode(RELAY, OUTPUT);
digitalWrite(LED, HIGH);
digitalWrite(RELAY, LOW);
pinMode(BUTTON, INPUT_PULLUP);
attachInterrupt(digitalPinToInterrupt(BUTTON), switchToggle, FALLING);
WiFi.begin(ssid, password);
int attempt = 0;
digitalWrite(LED, LOW);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
digitalWrite(LED, attempt++ % 2 == 0 ? LOW : HIGH);
}
digitalWrite(LED, LOW);
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("/", [](){
server.send(200, "text/plain", getSwitchState() == ON_STATE ? "On" : "Off");
});
server.on("/on", [](){
switchOn();
server.send(200, "text/plain", "On");
});
server.on("/off", [](){
switchOff();
server.send(200, "text/plain", "Off");
});
server.onNotFound(handleNotFound);
server.begin();
Serial.println("HTTP server started");
}
void loop() {
server.handleClient();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment