My goal is to have the physical button work even if there is no wifi, so i thought a simple webserver would handle the request but if all fails the button code still gets evaluated. The code below runs the loop for the physical button while listening for the webbutton... or so i thought
I'm not sure if it is simple and i just can't see it or if i am missing a concept here.
Can anybody help?
#include <ESP8266WiFi.h>
#include <ESP8266WebServer.h>
#define RELAY 5 // D1(GPIO5)
#define BUTTON 4 // D2(GPIO4)
ESP8266WebServer server;
char* ssid = "xxxxxxxx";
char* password = "xxxxxxxx";
bool currentState = false;
bool lastButtonState = false;
bool relayState = false;
String HTML_Root = "<!doctype html><html><body>\<a href=\'toggle\'><button type=\"button\">On/Off</button>\</body></html>";
void setup() {
Serial.begin(115200);
pinMode(BUTTON, INPUT);
pinMode(RELAY, OUTPUT);
// wifi
WiFi.mode(WIFI_STA);
WiFi.begin(ssid, password);
Serial.println("");
while (WiFi.status() != WL_CONNECTED) {
Serial.print(".");
delay(500);
}
Serial.println(WiFi.localIP());
// webserver
server.on ("/", handleRoot);
server.on("/toggle", handleWebButton);
server.begin();
}
void loop() {
server.handleClient();
handlePhysicalButton();
}
void handleRoot() {
server.send ( 200, "text/html", HTML_Root );
}
void handlePhysicalButton() {
currentState = digitalRead(BUTTON);
if (currentState != lastButtonState)
lastButtonState = currentState;
if (currentState) {
relayState = !relayState;
}
}
if (relayState) {
Serial.print("digitalRead(BUTTON)result -> HIGH!\n");
digitalWrite(RELAY, HIGH);
delay(500);
} else {
Serial.print("digitalRead(BUTTON)result -> LOW!\n");
digitalWrite(RELAY, LOW);
delay(500);
}
}
void handleWebButton() {
currentState = digitalRead(BUTTON);
lastButtonState = currentState;
Serial.print("Web button pressed!\n");
server.send(200, "text/html", HTML_Root);
}