ESP8266 NodeMCU Async Web Server – Control Outputs with Arduino IDE (ESPAsyncWebServer library)

In this tutorial you’ll learn how to build an asynchronous web server with the ESP8266 NodeMCU board to control its outputs. The board will be programmed using Arduino IDE, and we’ll use the ESPAsyncWebServer library.

ESP8266 NodeMCU Async Web Server Control Outputs with Arduino IDE ESPAsyncWebServer library

You might also like: ESP32 Async Web Server – Control Outputs with Arduino IDE (ESPAsyncWebServer library)

Asynchronous Web Server

To build the web server we’ll use the ESPAsyncWebServer library that provides an easy way to build an asynchronous web server. Building an asynchronous web server has several advantages as mentioned in the library GitHub page, such as:

  • “Handle more than one connection at the same time”;
  • “When you send the response, you are immediately ready to handle other connections while the server is taking care of sending the response in the background”;
  • “Simple template processing engine to handle templates”;
  • And much more.

Take a look at the library documentation on its GitHub page.

Parts Required

In this tutorial we’ll control three outputs. As an example, we’ll control LEDs. So, you need the following parts:

You can use the preceding links or go directly to MakerAdvisor.com/tools to find all the parts for your projects at the best price!

Schematic

Before proceeding to the code, wire 3 LEDs to the ESP8266. We’re connecting the LEDs to GPIOs 5, 4 and 2, but you can use any other GPIOs (read ESP8266 NodeMCU GPIO Reference Guide).

ESP8266 NodeMCU Arduino Outputs Async ESPAsyncWebServer library wiring schematic diagram

Installing Libraries – ESP Async Web Server

To build the web server you need to install the following libraries. Click the links below to download the 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.

Project Overview

To better understand the code, let’s see how the web server works.

ESP8266 NodeMCU Async Web Server Control Outputs
  • The web server contains one heading “ESP Web Server” and three buttons (toggle switches) to control three outputs. Each slider button has a label indicating the GPIO output pin. You can easily remove/add more outputs.
  • When the slider is red, it means the output is on (its state is HIGH). If you toggle the slider, it turns off the output (change the state to LOW).
  • When the slider is gray, it means the output is off (its state is LOW). If you toggle the slider, it turns on the output (change the state to HIGH).

How it Works?

ESP8266 NodeMCU Async Web Server Project Overview ESPAsyncWebServer Library

Let’s see what happens when you toggle the buttons. We’ll see the example for GPIO 2. It works similarly for the other buttons.

1. In the first scenario, you toggle the button to turn GPIO 2 on. When that happens, it makes an HTTP GET request on the /update?output=2&state=1 URL. Based on that URL, we change the state of GPIO 2 to 1 (HIGH) and turn the LED on.

2. In the second example, when you toggle the button to turn GPIO 2 off. When that happens, make an HTTP GET request on the /update?output=2&state=0 URL. Based on that URL, we change the state of GPIO 2 to 0 (LOW) and turn the LED off.

Code for ESP Async Web Server

Copy the following code to your Arduino IDE.

/*********
  Rui Santos
  Complete project details at https://RandomNerdTutorials.com/esp8266-nodemcu-async-web-server-espasyncwebserver-library/
  The above copyright notice and this permission notice shall be included in all
  copies or substantial portions of the Software.
*********/

// Import required libraries
#include <ESP8266WiFi.h>
#include <ESPAsyncTCP.h>
#include <ESPAsyncWebServer.h>

// Replace with your network credentials
const char* ssid = "REPLACE_WITH_YOUR_SSID";
const char* password = "REPLACE_WITH_YOUR_PASSWORD";

const char* PARAM_INPUT_1 = "output";
const char* PARAM_INPUT_2 = "state";

// Create AsyncWebServer object on port 80
AsyncWebServer server(80);

const char index_html[] PROGMEM = R"rawliteral(
<!DOCTYPE HTML><html>
<head>
  <title>ESP Web Server</title>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="icon" href="data:,">
  <style>
    html {font-family: Arial; display: inline-block; text-align: center;}
    h2 {font-size: 3.0rem;}
    p {font-size: 3.0rem;}
    body {max-width: 600px; margin:0px auto; padding-bottom: 25px;}
    .switch {position: relative; display: inline-block; width: 120px; height: 68px} 
    .switch input {display: none}
    .slider {position: absolute; top: 0; left: 0; right: 0; bottom: 0; background-color: #ccc; border-radius: 6px}
    .slider:before {position: absolute; content: ""; height: 52px; width: 52px; left: 8px; bottom: 8px; background-color: #fff; -webkit-transition: .4s; transition: .4s; border-radius: 3px}
    input:checked+.slider {background-color: #b30000}
    input:checked+.slider:before {-webkit-transform: translateX(52px); -ms-transform: translateX(52px); transform: translateX(52px)}
  </style>
</head>
<body>
  <h2>ESP Web Server</h2>
  %BUTTONPLACEHOLDER%
<script>function toggleCheckbox(element) {
  var xhr = new XMLHttpRequest();
  if(element.checked){ xhr.open("GET", "/update?output="+element.id+"&state=1", true); }
  else { xhr.open("GET", "/update?output="+element.id+"&state=0", true); }
  xhr.send();
}
</script>
</body>
</html>
)rawliteral";

// Replaces placeholder with button section in your web page
String processor(const String& var){
  //Serial.println(var);
  if(var == "BUTTONPLACEHOLDER"){
    String buttons = "";
    buttons += "<h4>Output - GPIO 5</h4><label class=\"switch\"><input type=\"checkbox\" onchange=\"toggleCheckbox(this)\" id=\"5\" " + outputState(5) + "><span class=\"slider\"></span></label>";
    buttons += "<h4>Output - GPIO 4</h4><label class=\"switch\"><input type=\"checkbox\" onchange=\"toggleCheckbox(this)\" id=\"4\" " + outputState(4) + "><span class=\"slider\"></span></label>";
    buttons += "<h4>Output - GPIO 2</h4><label class=\"switch\"><input type=\"checkbox\" onchange=\"toggleCheckbox(this)\" id=\"2\" " + outputState(2) + "><span class=\"slider\"></span></label>";
    return buttons;
  }
  return String();
}

String outputState(int output){
  if(digitalRead(output)){
    return "checked";
  }
  else {
    return "";
  }
}

void setup(){
  // Serial port for debugging purposes
  Serial.begin(115200);

  pinMode(5, OUTPUT);
  digitalWrite(5, LOW);
  pinMode(4, OUTPUT);
  digitalWrite(4, LOW);
  pinMode(2, OUTPUT);
  digitalWrite(2, LOW);
  
  // Connect to Wi-Fi
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) {
    delay(1000);
    Serial.println("Connecting to WiFi..");
  }

  // Print ESP Local IP Address
  Serial.println(WiFi.localIP());

  // Route for root / web page
  server.on("/", HTTP_GET, [](AsyncWebServerRequest *request){
    request->send_P(200, "text/html", index_html, processor);
  });

  // Send a GET request to <ESP_IP>/update?output=<inputMessage1>&state=<inputMessage2>
  server.on("/update", HTTP_GET, [] (AsyncWebServerRequest *request) {
    String inputMessage1;
    String inputMessage2;
    // GET input1 value on <ESP_IP>/update?output=<inputMessage1>&state=<inputMessage2>
    if (request->hasParam(PARAM_INPUT_1) && request->hasParam(PARAM_INPUT_2)) {
      inputMessage1 = request->getParam(PARAM_INPUT_1)->value();
      inputMessage2 = request->getParam(PARAM_INPUT_2)->value();
      digitalWrite(inputMessage1.toInt(), inputMessage2.toInt());
    }
    else {
      inputMessage1 = "No message sent";
      inputMessage2 = "No message sent";
    }
    Serial.print("GPIO: ");
    Serial.print(inputMessage1);
    Serial.print(" - Set to: ");
    Serial.println(inputMessage2);
    request->send(200, "text/plain", "OK");
  });

  // Start server
  server.begin();
}

void loop() {

}

View raw code

How the Code Works

In this section we’ll explain how the code works. Keep reading if you want to learn more or jump to the Demonstration section to see the final result.

Importing libraries

First, import the required libraries. You need to include the WiFi, ESPAsyncWebserver and the ESPAsyncTCP libraries.

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

Setting your network credentials

Insert your network credentials in the following variables, so that the ESP8266 can connect to your local network.

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

Input Parameters

To check the parameters passed on the URL (GPIO number and its state), we create two variables, one for the output and other for the state.

const char* PARAM_INPUT_1 = "output";
const char* PARAM_INPUT_2 = "state";

Remember that the ESP8266 receives requests like this: /update?output=2&state=0

AsyncWebServer object

Create an AsyncWebServer object on port 80.

AsyncWebServer server(80);

Building the Web Page

All the HTML text with styles and JavaScript is stored in the index_html variable. Now we’ll go through the HTML text and see what each part does.

The title goes inside the <title> and </tile> tags. The title is exactly what it sounds like: the title of your document, which shows up in your web browser’s title bar. In this case, it is “ESP Web Server”.

<title>ESP Web Server</title>
ESP32 Async Web Server web page title HTML

The following <meta> tag makes your web page responsive in any browser (laptop, tablet or smartphone).

<meta name="viewport" content="width=device-width, initial-scale=1">

The next line prevents requests on the favicon. In this case, we don’t have a favicon. The favicon is the website icon that shows next to the title in the web browser tab. If we don’t add the following line, the ESP will receive a request for the favicon every time we access the web server.

<link rel="icon" href="data:,">

Between the <style></style> tags, we add some CSS to style the web page. We won’t go into detail on how this CSS styling works.

<style>
    html {font-family: Arial; display: inline-block; text-align: center;}
    h2 {font-size: 3.0rem;}
    p {font-size: 3.0rem;}
    body {max-width: 600px; margin:0px auto; padding-bottom: 25px;}
    .switch {position: relative; display: inline-block; width: 120px; height: 68px} 
    .switch input {display: none}
    .slider {position: absolute; top: 0; left: 0; right: 0; bottom: 0; background-color: #ccc; border-radius: 6px}
    .slider:before {position: absolute; content: ""; height: 52px; width: 52px; left: 8px; bottom: 8px; background-color: #fff; -webkit-transition: .4s; transition: .4s; border-radius: 3px}
    input:checked+.slider {background-color: #b30000}
    input:checked+.slider:before {-webkit-transform: translateX(52px); -ms-transform: translateX(52px); transform: translateX(52px)}
</style>

HTML Body

Inside the <body></body> tags is where we add the web page content.

The <h2></h2> tags add a heading to the web page. In this case, the “ESP Web Server” text, but you can add any other text.

<h2>ESP Web Server</h2>

After the heading, we have the buttons. The way the buttons show up on the web page (red: if the GPIO is on; or gray: if the GPIO is off) varies depending on the current GPIO state.

When you access the web server page, you want it to show the right current GPIO states. So, instead of adding the HTML text to build the buttons, we’ll add a placeholder %BUTTONPLACEHOLDER%. This palceholder will then be replaced with the actual HTML text to build the buttons with the right states, when the web page is loaded.

%BUTTONPLACEHOLDER%

JavaScript

Then, there’s some JavaScript that is responsible to make an HTTP GET request when you toggle the buttons as we’ve explained previously.

<script>function toggleCheckbox(element) {
  var xhr = new XMLHttpRequest();
  if(element.checked){ xhr.open("GET", "/update?output="+element.id+"&state=1", true); }
  else { xhr.open("GET", "/update?output="+element.id+"&state=0", true); }
  xhr.send();
}
</script>

Here’s the line that makes the request:

if(element.checked){ xhr.open("GET", "/update?output="+element.id+"&state=1", true); }

element.id returns the id of an HTML element. The id of each button will be the GPIO controlled as we’ll see in the next section:

  • GPIO 5 button » element.id = 5
  • GPIO 4 button » element.id = 4
  • GPIO 2 button » element.id = 2

Processor

Now, we need to create the processor() function, that replaces the placeholders in the HTML text with what we define.

When the web page is requested, check if the HTML has any placeholders. If it finds the %BUTTONPLACEHOLDER% placeholder, it returns the HTML text to create the buttons.

String processor(const String& var){
  //Serial.println(var);
  if(var == "BUTTONPLACEHOLDER"){
    String buttons = "";
    buttons += "<h4>Output - GPIO 5</h4><label class=\"switch\"><input type=\"checkbox\" onchange=\"toggleCheckbox(this)\" id=\"5\" " + outputState(5) + "><span class=\"slider\"></span></label>";
    buttons += "<h4>Output - GPIO 4</h4><label class=\"switch\"><input type=\"checkbox\" onchange=\"toggleCheckbox(this)\" id=\"4\" " + outputState(4) + "><span class=\"slider\"></span></label>";
    buttons += "<h4>Output - GPIO 2</h4><label class=\"switch\"><input type=\"checkbox\" onchange=\"toggleCheckbox(this)\" id=\"2\" " + outputState(2) + "><span class=\"slider\"></span></label>";
    return buttons;
  }
  return String();
}

You can easily delete or add more lines to create more buttons.

Let’s take a look at how the buttons are created. We create a String variable called buttons that contains the HTML text to build the buttons. We concatenate the HTML text with the current output state so that the toggle button is either gray or red. The current output state is returned by the outputState(<GPIO>) function (it accepts as argument the GPIO number). See below:

buttons += "<h4>Output - GPIO 2</h4><label class=\"switch\"><input type=\"checkbox\" onchange=\"toggleCheckbox(this)\" id=\"2\" " + outputState(2) + "><span class=\"slider\"></span></label>";

The \ is used so that we can pass “” inside the String.

The outputState() function returns either “checked” if the GPIO is on or and empty field “” if the GPIO is off.

String outputState(int output){
  if(digitalRead(output)){
    return "checked";
  }
  else {
    return "";
  }
}

So, the HTML text for GPIO 2 when it is on, would be:

<h4>Output - GPIO 2</h4>
<label class="switch">
<input type="checkbox" onchange="toggleCheckbox(this)" id="2" checked><span class="slider"></span>
</label>

Let’s break this down into smaller sections to understand how it works.

In HTML, a toggle switch is an input type. The <input> tag specifies an input field where the user can enter data. The toggle switch is an input field of type checkbox. There are many other input field types.

<input type="checkbox">

The checkbox can be checked or not. When it is check, you have something as follows:

<input type="checkbox" checked>

The onchange is an event attribute that occurs when we change the value of the element (the checkbox). Whenever you check or uncheck the toggle switch, it calls the toggleCheckbox() JavaScript function for that specific element id (this).

The id specifies a unique id for that HTML element. The id allows us to manipulate the element using JavaScript or CSS.

<input type="checkbox" onchange="toggleCheckbox(this)" id="2" checked>

setup()

In the setup() initialize the Serial Monitor for debugging purposes.

Serial.begin(115200);

Set the GPIOs you want to control as outputs using the pinMode() function and set them to LOW when the ESP8266 first starts. If you’ve added more GPIOs, do the same procedure.

pinMode(2, OUTPUT);
pinMode(5, OUTPUT);
digitalWrite(5, LOW);
pinMode(4, OUTPUT);
digitalWrite(4, LOW);
pinMode(2, OUTPUT);
digitalWrite(2, LOW);

Connect to your local network and print the ESP8266 IP address.

WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
  delay(1000);
  Serial.println("Connecting to WiFi..");
}

// Print ESP Local IP Address
Serial.println(WiFi.localIP());

In the setup(), you need to handle what happens when the ESP8266 receives requests. As we’ve seen previously, you receive a request of this type:

<ESP_IP>/update?output=<inputMessage1>&state=<inputMessage2>

So, we check if the request contains the PARAM_INPUT1 variable value (output) and the PARAM_INPUT2(state) and save the corresponding values on the input1Message and input2Message variables.

if (request->hasParam(PARAM_INPUT_1) && request->hasParam(PARAM_INPUT_2)) {
  inputMessage1 = request->getParam(PARAM_INPUT_1)->value();
  inputMessage2 = request->getParam(PARAM_INPUT_2)->value();

Then, we control the corresponding GPIO with the corresponding state (the inputMessage1 variable saves the GPIO number and the inputMessage2 saves the state – 0 or 1)

digitalWrite(inputMessage1.toInt(), inputMessage2.toInt());

Here’s the complete code to handle the HTTP GET /update request:

server.on("/update", HTTP_GET, [] (AsyncWebServerRequest *request) {
  String inputMessage1;
  String inputMessage2;
  // GET input1 value on <ESP_IP>/update?output=<inputMessage1>&state=<inputMessage2>
  if (request->hasParam(PARAM_INPUT_1) && request->hasParam(PARAM_INPUT_2)) {
    inputMessage1 = request->getParam(PARAM_INPUT_1)->value();
    inputMessage2 = request->getParam(PARAM_INPUT_2)->value();
    digitalWrite(inputMessage1.toInt(), inputMessage2.toInt());
  }
  else {
    inputMessage1 = "No message sent";
    inputMessage2 = "No message sent";
  }
  Serial.print("GPIO: ");
  Serial.print(inputMessage1);
  Serial.print(" - Set to: ");
  Serial.println(inputMessage2);
  request->send(200, "text/plain", "OK");
});

Finally, start the server:

server.begin();

Demonstration

After uploading the code to your ESP8266, open the Serial Monitor at a baud rate of 115200. Press the on-board RST/EN button. You should get its IP address.

Open a browser and type the ESP IP address. You’ll get access to a similar web page.

ESP8266 NodeMCU Async Web Server Web Browser Switch Buttons

Press the toggle buttons to control the ESP GPIOs. At the same time, you should get the following messages in the Serial Monitor to help you debug your code.

ESP8266 NodeMCU Async Web Server Arduino IDE Serial Monitor

You can also access the web server from a browser in your smartphone. Whenever you open the web server, it shows the current GPIO states. Red indicates the GPIO is on, and gray that the GPIO is off.

ESP8266 NodeMCU Async Web Server Web Browser Switch Buttons Mobile Responsive

Wrapping Up

In this tutorial you’ve learned how to create an asynchronous web server with the ESP8266 NodeMCU to control its outputs using toggle switches. Whenever you open the web page, it shows the updated GPIO states.

We have other web server examples using the ESPAsyncWebServer library that you may like:

We hope you found this tutorial useful. If you have any questions, post a comment below and we’ll try to get back to you.

If you like ESP8266, you might consider enrolling in our eBook “Home Automation using ESP8266“. You can also access our free ESP8266 resources here.

Thank you 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!

33 thoughts on “ESP8266 NodeMCU Async Web Server – Control Outputs with Arduino IDE (ESPAsyncWebServer library)”

  1. Not getting IP but am getting connecting to WIFI. Using WeMos D1 Mini loaded on ide WeMos D1 R1 , using Arduino 1.8.13 software. Pressed reset but all I see is same message “connecting to WIFI”. Thanks

    Reply
  2. So I left you a message about my WeMos board just saying “conning to WiFi on Oct 23 , never got a response from you. Do you have a suggestion as to what I need to do?

    Reply
  3. Dear
    First of all, I would like to compliment you because you have really good examples for practice. I am a beginner in programming ESP modules and your examples are really for me to learn.
    I would like to combine two of your examples: to read the BME sensor (ESP8266 NodeMCU Web Server using Server-Sent Events) and to have three relays under control (ESP8266 NodeMCU Async Web Server – Control Outputs with Arduino IDE).
    I’ve tried many times, but I can’t.
    Im asking for help.
    Thanks in advance
    Bojan

    Reply
  4. I have tried this on 2 different units, a D1 Mini and a Esp8266 esp12 module. I must be doing something wrong, have not gotten this to work, all i get is unreadable characters. Can you please assist me with this?

    Reply
    • Just an edit to my above message, I forgot to change baud rate but all I get is connecting to wifi , I know my ssid and password are correct.

      Reply
    • Hi Larry.
      Please check the baud rate of your Serial Monitor.
      It must be set to 115200.
      After opening the Serial Monitor press the on-board RST button.
      The first thing you’ll see is a bunch of unreadable characters. After that, you should get “normal” messages.
      Regards,
      Sara

      Reply
      • Sara, thanks for the reply, to answer your question, no. It is not working, I figured out that the baud rate was wrong but that in its self didn’t solve the problem.All I get is “Connecting to WiFi..
        I have checked all settings and they are correct .

        Reply
  5. Sara;
    Thank you for your answer, but no it is not working yet. All I get is Connecting to WiFi. I know that this board works because I ran another sketch on it and it sees that I connected to my wifi on 192.168.4.1.So I am confident that the board does work but for some reason loading your sketch with my credentials only shows that message “Connecting to WiFi..” like it dosen’t find a connection.

    Reply
  6. I have tried to code a favicon. I have favicon.ino file in main code directory. Line in code has changed to:

    But favicon does not appear in Webpage tab.

    Reply
  7. I have tried to code a favicon. I have favicon.ino file in main code directory. Line in code has changed to:
    /* < link rel = “icon” href = “favicon.ico” > */

    But favicon does not appear in Webpage tab.

    Reply
  8. So now I have tried this on 3 separate boards, one just removed from sealed anti static packaging. Just tells me” Connecting to WiFi” but for some reason , it never gets there.I also tried you suggestion to run a different sketch Wifi Scan and the WeMos found 3 networks ,the ESP 8266 LoLin board found 4 , the 4th was not mine. Sorry for being such a burden, I was interested in signing up for your program lessons and decided to try this sketch . Not having any luck though, thanks again for taking the time with this

    Reply
    • Hi Larry.
      I’m sorry for that issue.
      If the board can’t find your network, it won’t be able to connect to it.
      That’s probably your issue.
      If you try with the other board that finds your network, it will be able to connect.
      Regards,
      Sara

      Reply
      • Thanks, that is why I tried 3 different boards, they all find my network as described above but none of them work when I load your sketch. Can’t get any easier than that, cut, paste, credentials , it should just load and work. I am totally lost here. It would be tough to try to learn anything when cutting and pasting code don’t do what it is supposed to do. Not saying your code at all .

        Reply
        • I’m sorry.
          But I have no idea what might be causing the issue.
          Your issue usually is related with wrong network credentials: either the SSID name or the password.

          Reply
          • Thanks for trying, I can’t figure it out either, if I do I will post the results. I know my credentials are correct otherwise I would see same issues on other devices, and I am literally on top of my wireless router. Thanks again

  9. Sara, got project up and running, thanks for your help. Turns out that I was not putting router name all in caps(egg of face), for some reason all my home devices ,Alexa, TV, ChromeCast, Iphones and such don’t care if the name is in caps or not. Can’t explain why this is but it obviously matters here. Thanks again for your patience and help, kind of embarrassing to miss that but I did. Lesson learned, looking forward to possibly join your classes .

    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.