ESP32/ESP8266 Web Server: Control Outputs with Momentary Switch

This tutorial shows how to create a web server with a button that acts as momentary switch to remotely control ESP32 or ESP8266 outputs. The output state is HIGH as long as you keep holding the button in your web page. Once you release it, it changes to LOW. As an example, we’ll control an LED, but you can control any other output.

ESP32 ESP8266 Web Server Control Outputs with Momentary Switch Arduino IDE

The ESP32/ESP8266 boards will be programmed using Arduino IDE. So make sure you have these boards installed:

Project Overview

The following diagram shows a simple overview of the project we’ll build.

Momentary switch web server esp32 esp8266 project overview
  • The ESP32 or ESP8266 hosts a web server that you can access to control an output;
  • The output’s default state is LOW, but you can change it depending on your project application;
  • There’s a button that acts like a momentary switch:
    • if you press the button, the output changes its state to HIGH as long as you keep holding the button;
    • once the button is released, the output state goes back to LOW.

Installing Libraries – Async Web Server

To build the web server you need to install the following libraries:

These libraries aren’t available to install through the Arduino Library Manager, so you need to copy the library files to the Arduino Installation Libraries folder. Alternatively, in your Arduino IDE, you can go to Sketch Include Library > Add .zip Library and select the libraries you’ve just downloaded.

Code

Copy the following code to your Arduino IDE.

/*********
  Rui Santos
  Complete project details at https://RandomNerdTutorials.com/esp32-esp8266-web-server-outputs-momentary-switch/
  
  Permission is hereby granted, free of charge, to any person obtaining a copy
  of this software and associated documentation files.
  
  The above copyright notice and this permission notice shall be included in all
  copies or substantial portions of the Software.
*********/

#ifdef ESP32
  #include <WiFi.h>
  #include <AsyncTCP.h>
#else
  #include <ESP8266WiFi.h>
  #include <ESPAsyncTCP.h>
#endif
#include <ESPAsyncWebServer.h>

// REPLACE WITH YOUR NETWORK CREDENTIALS
const char* ssid = "REPLACE_WITH_YOUR_SSID";
const char* password = "REPLACE_WITH_YOUR_PASSWORD";

const int output = 2;

// HTML web page
const char index_html[] PROGMEM = R"rawliteral(
<!DOCTYPE HTML><html>
  <head>
    <title>ESP Pushbutton Web Server</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <style>
      body { font-family: Arial; text-align: center; margin:0px auto; padding-top: 30px;}
      .button {
        padding: 10px 20px;
        font-size: 24px;
        text-align: center;
        outline: none;
        color: #fff;
        background-color: #2f4468;
        border: none;
        border-radius: 5px;
        box-shadow: 0 6px #999;
        cursor: pointer;
        -webkit-touch-callout: none;
        -webkit-user-select: none;
        -khtml-user-select: none;
        -moz-user-select: none;
        -ms-user-select: none;
        user-select: none;
        -webkit-tap-highlight-color: rgba(0,0,0,0);
      }  
      .button:hover {background-color: #1f2e45}
      .button:active {
        background-color: #1f2e45;
        box-shadow: 0 4px #666;
        transform: translateY(2px);
      }
    </style>
  </head>
  <body>
    <h1>ESP Pushbutton Web Server</h1>
    <button class="button" onmousedown="toggleCheckbox('on');" ontouchstart="toggleCheckbox('on');" onmouseup="toggleCheckbox('off');" ontouchend="toggleCheckbox('off');">LED PUSHBUTTON</button>
   <script>
   function toggleCheckbox(x) {
     var xhr = new XMLHttpRequest();
     xhr.open("GET", "/" + x, true);
     xhr.send();
   }
  </script>
  </body>
</html>)rawliteral";

void notFound(AsyncWebServerRequest *request) {
  request->send(404, "text/plain", "Not found");
}

AsyncWebServer server(80);

void setup() {
  Serial.begin(115200);
  WiFi.mode(WIFI_STA);
  WiFi.begin(ssid, password);
  if (WiFi.waitForConnectResult() != WL_CONNECTED) {
    Serial.println("WiFi Failed!");
    return;
  }
  Serial.println();
  Serial.print("ESP IP Address: http://");
  Serial.println(WiFi.localIP());
  
  pinMode(output, OUTPUT);
  digitalWrite(output, LOW);
  
  // Send web page to client
  server.on("/", HTTP_GET, [](AsyncWebServerRequest *request){
    request->send_P(200, "text/html", index_html);
  });

  // Receive an HTTP GET request
  server.on("/on", HTTP_GET, [] (AsyncWebServerRequest *request) {
    digitalWrite(output, HIGH);
    request->send(200, "text/plain", "ok");
  });

  // Receive an HTTP GET request
  server.on("/off", HTTP_GET, [] (AsyncWebServerRequest *request) {
    digitalWrite(output, LOW);
    request->send(200, "text/plain", "ok");
  });
  
  server.onNotFound(notFound);
  server.begin();
}

void loop() {
 
}

View raw code

You just need to enter your network credentials (SSID and password) and the web server will work straight away. The code is compatible with both the ESP32 and ESP8266 boards and controls the on-board LED GPIO 2 – you can change the code to control any other GPIO.

How the Code Works

We’ve already explained in great details how web servers like this work in previous tutorials (DHT Temperature Web Server), so we’ll just take a look at the relevant parts for this project.

Network Credentials

As said previously, you need to insert your network credentials in the following lines:

const char* ssid = "REPLACE_WITH_YOUR_SSID";
const char* password = "REPLACE_WITH_YOUR_PASSWORD";

Momentary Switch Button (web server)

The following line creates the momentary switch button.

<button class="button" onmousedown="toggleCheckbox('on');" ontouchstart="toggleCheckbox('on');" onmouseup="toggleCheckbox('off');" ontouchend="toggleCheckbox('off');">LED PUSHBUTTON</button>

Let’s break this down into small parts.

In HTML, to create a button, use the <button></button> tags. In between you write the button text. For example:

<button>LED PUSHBUTTON</button>

The button can have several attributes. In HTML, the attributes provide additional information about HTML elements, in this case, about the button.

Here, we have the following attributes:

class: provides a class name for the button. This way, it can be used by CSS or JavaScript to perform certain tasks for the button. In this case, it is used to format the button using CSS. The class attribute has the name “button”, but you could have called it any other name.

<button class="button">LED PUSHBUTTON</button>

onmousedown: this is an event attribute. It executes a JavaScript function when you press the button. In this case it calls toggleCheckbox(‘on’). This function makes a request to the ESP32/ESP8266 on a specific URL, so that it knows it needs to change the output state to HIGH.

ontouchstart: this is an event attribute similar to the previous one, but it works for devices with a touch screen like a smartphone or table. It calls the same JavaScript function to change the output state to HIGH.

onmouseup: this is an event attribute that executes a JavaScript function when you release the mouse over the button. In this case, it calls toggleCheckbox(‘off’). This function makes a request to the ESP32/ESP8266 on a specific URL, so that it knows it needs to change the output state to LOW.

ontouchend: similar to the previous attribute but for devices with touchscreen.

So, in the end, our button looks like this:

<button class="button" onmousedown="toggleCheckbox('on');" ontouchstart="toggleCheckbox('on');" onmouseup="toggleCheckbox('off');" ontouchend="toggleCheckbox('off');">LED PUSHBUTTON</button>

HTTP GET Request to Change Button State (JavaScript)

We’ve seen previously, that when you press or release the button, the toggleCheckbox() function is called. You either pass the “on” or “off” arguments, depending on the state you want.

That function, makes an HTTP request to the ESP32 either on the /on or /off URLs:

function toggleCheckbox(x) {
  var xhr = new XMLHttpRequest();
  xhr.open("GET", "/" + x, true);
  xhr.send();
}

Handle Requests

Then, we need to handle what happens when the ESP32 or ESP8266 receives requests on those URLs.

When a request is received on the /on URL, we turn the GPIO on (HIGH) as shown below:

server.on("/on", HTTP_GET, [] (AsyncWebServerRequest *request) {
  digitalWrite(output, HIGH);
  request->send(200, "text/plain", "ok");
});

When a request is received on the /off URL, we turn the GPIO off (LOW):

server.on("/off", HTTP_GET, [] (AsyncWebServerRequest *request) {
  digitalWrite(output, LOW);
  request->send(200, "text/plain", "ok");
});

Demonstration

Upload the code to your ESP32 or ESP8266 board.

Then, open the Serial Monitor at a baud rate of 115200. Press the on-board EN/RST button to get is IP address.

ESP32 ESP8266 Web Server Demonstration IP Address Arduino IDE Serial Monitor

Open a browser on your local network, and type the ESP IP address. You should have access to the web server as shown below.

Momentary Switch Web Server ESP32 and ESP8266 Arduino IDE Demonstration

The on-board LED stays on as long as you keep holding down the button on the web page.

Note: it works the other way around for the ESP8266 because the on-board LED works with inverted logic.

ESP32 board Built in LED turned on HIGH

When you release the button, the LED goes back to its default state (LOW).

ESP32 board Built in LED turned off LOW

Watch the next quick video for a live demonstration:


Wrapping Up

In this tutorial you’ve learned how to add event attributes to the buttons on your web server to make them act as momentary switches. This allows you to change the default’s output state as long as you’re pressing the button.

Other projects you may like:

Learn more about the ESP32 and ESP8266 with our resources:

Thanks for reading.


Learn how to program and build projects with the ESP32 and ESP8266 using MicroPython firmware DOWNLOAD »

Learn how to program and build projects with the ESP32 and ESP8266 using MicroPython firmware DOWNLOAD »


Enjoyed this project? Stay updated by subscribing our weekly newsletter!

3 thoughts on “ESP32/ESP8266 Web Server: Control Outputs with Momentary Switch”

  1. I have tried the ESP32 project first with interest without any adaptation to the script. I noticed that the LED often stays on after a short press of the button and although the button was released. I was planning to use it as a pulse relay but it doesn’t work as expected. Maybe there is another solution for a pulse relay?

    Reply
  2. Sorry to bother but you have a small mistake in the code.
    The logical values applied to the LED pin should be inverted due to internal pullup!

    Thank you

    Reply

Leave a Comment

Download our Free eBooks and Resources

Get instant access to our FREE eBooks, Resources, and Exclusive Electronics Projects by entering your email address below.