Read & Display Switch State on Web Page with ESP8266 Web Server

Reading state of a switch or push button or even sensor state and displaying this information on the web page is essential in many Internet of Things applications. For example, monitoring whether somebody has pressed the button/switch and displaying that information on the web page. Or, when creating an laser based alarm system when somebody crosses the laser beam and displaying that information on the web page is another application example. Here, we illustrate how to read and display the state of a physical switch over the internet using ESP8266 ESP12E WiFi module based web server. Other wifi modules like NodeMCU or ESP32 module can also be used following this example.

Web Page with ESP8266 Web Server

 

 

 

 

 

 

 

 

 

 

 To read the switch state and display on web page using ESP12E based web server we will create an asynchronous web server using the ESPAsyncWebServer and ESPAsyncTCP libraries and utilize template placeholder. For ESP32 you will need to use AsyncTCP library instead of ESPAsyncTCP. We have already explained about these libraries in the tutorial Simple ESP8266 Asynchronous Web Server Example with Code.

Recommended Prerequisite Tutorials

Interfacing and Schematic Diagram

The following picture switch(whose state will displayed on a web page) connected to GPIO13 of ESP12E WiFi module on a breadboard.

ESP8266 web server with switch

Video Demonstration of ESP8266 web server

The following video demonstrates how to read and display a physical switch state on a breadboard on a web page using ESP8266 web server.

Schematic Wiring Drawing

The following shows the schematic diagram connecting the ESP8266 web server with switch connected to it on GPIO13.

schematic diagram of ESP8266 web server with switch

Program Code for ESP8266 Web Server for Reading Switch State

The following is the program code that configures ESP8266 as an asynchronous web server and which monitors the state of a physical switch and display that state information(on or off) on the web page.

#include <ESPAsyncTCP.h>
#include <ESPAsyncWebServer.h>

const int switchPin = 13;

const char ssid[]="SSID";
const char password[]="PASSWORD";

const char switchWebPage[] PROGMEM = R"=====(
<html>
  <head>
    <title>Read Switch State Web Page</title>
    <meta http-equiv="refresh" content="3">

    <style>
      body{
          padding: 40px;
          text-align: center;
        }
    </style>
    
  </head>
  <body>
    <p>Switch State:</p>
    <p><b>%state%</b></p>
  </body>
</html>

)=====";

AsyncWebServer server(80);

String processor(const String& var){
  String switch_state;

  if(var=="state"){
    if(digitalRead(switchPin)){
      switch_state = "OFF";
      printf("Switch Off\n");
      }
    else{
      switch_state = "ON";
      printf("Switch On\n");
      }
    return switch_state;
    }
  return String();
  }

void setup() {
  pinMode(switchPin, INPUT_PULLUP);
  Serial.begin(115200);

  Serial.printf("Connecting to %s....\n", ssid);
  WiFi.mode(WIFI_STA);
  WiFi.begin(ssid, password);
  if(WiFi.waitForConnectResult() != WL_CONNECTED){
    Serial.printf("WiFi connection failed!\n");
    }
  Serial.printf("Connected to %s\n", ssid);
  Serial.printf("IP address: %s\n", WiFi.localIP().toString().c_str());

  server.on("/", HTTP_GET, [](AsyncWebServerRequest *request){
    request->send_P(200, "text/html", switchWebPage, processor);
    }
    );

  server.begin();
}

void loop() {

}

In the above program code, we have done the followings:

1. We have included the ESPAsyncWebServer and ESPAsynchTCP libraries to build the asynchronous web server. 

#include <ESPAsyncTCP.h>
#include <ESPAsyncWebServer.h>

2. We have created an alias switchPin for the GPIO pin 13

const int switchPin = 13;

3. Then we have setup the WiFi network credentials

Note that this must be replaced with your own WiFi SSID and PASSWORD credentials.

const char ssid[]="SSID";
const char password[]="PASSWORD";

4. We have stored our HTML code inside the character array called switchWebPage in the program memory space as string literal. In the HTML code we have used http-equiv="refresh" with content="3" to refresh the web page every 3 seconds. Then we have used some CSS code using <style> to center the displayed text on the center and below the top of 40px. In the body section we have used the %state% template placeholder that will be updated with either ON or OFF according to the state of the switch. This is coded in the processor in the setup() function later on.

const char switchWebPage[] PROGMEM = R"=====(
<html>
  <head>
    <title>Read Switch State Web Page</title>
    <meta http-equiv="refresh" content="3">

    <style>
      body{
          padding: 40px;
          text-align: center;
        }
    </style>
    
  </head>
  <body>
    <p>Switch State:</p>
    <p><b>%state%</b></p>
  </body>
</html>

)=====";

5. Using AsyncWebServer server(80) we have create server object with port number 80.

6. We then have created the processor() function that handles the template state event change. This function returns string which is either ON or OFF which is saved in the string variable switch_state.

String processor(const String& var){
  String switch_state;

  if(var=="state"){
    if(digitalRead(switchPin)){
      switch_state = "OFF";
      printf("Switch Off\n");
      }
    else{
      switch_state = "ON";
      printf("Switch On\n");
      }
    return switch_state;
    }
  return String();
  }

7. In the setup() function, we have first set up the switch pin to input with internal pullup and set the baud rate of 115200 for serial communication with the ESP12E wifi module. 

We then print message to the user "connecting to... " ssid provided to inform progress of connection behind the scene which users can see on the Arduino IDE serial monitor. Using WiFi.mode() we have setup the ESP8266mod into Station mode.  Using if(WiFi.waitForConnectResult() ) statement we check for wifi connection to Access Point(AP). If the connection fails then we print message "WiFi connection failed!\n" to inform users that connection has failed. If the connection is successful, we print out message "Connected to " ssid and also print out the IP address to inform the user at which IP address it is connected to. 

Using the on method of object server, server.on() , we create a handler that handles the HTTP request from incoming clients. Whenever there is request, we send the content of the switchWebPage stored in the program space.

server.on("/", HTTP_GET, [](AsyncWebServerRequest *request){
    request->send_P(200, "text/html", switchWebPage, processor);
    }
    );

 When the client changes the state of the switch either ON or OFF, the server.on detects it and handles it. The handler provokes the processor(). The processor() based on the switch state event, returns the state of the switch either ON or OFF and it gets displayed on the web page by using the state placeholder on the web page.

8. Finally the server.begin() is used to start the asynchronous web server.

Thus in this ESP8266 Web Server tutorial we have used template placeholder concept and applied to read the physical state of switch(button) and display the state on the web page using ESP8266 web server. This is useful in making IoT application where sensor data has to be shown on web page.

Post a Comment

Previous Post Next Post