ESP32 Asynchronous web server
We often need a graphical way to interact with an application running on an ESP32 microcontroller, whether to change its settings or display sensor readings. A web browser is a natural choice, since our smartphone is usually close at hand. An asynchronous web server helps us build this kind of interface.
Difficulty: Intermediate
Created: January 2023
Reviewed: September 2026
Reference platform: ESP32 WROOM module
In this article, I will use practical examples to show how the ESPAsyncWebServer library works on an ESP32 WROOM module. Every example has been tested on hardware.
Contents:
Getting started with ESPAsyncWebServer
Sending form data with the POST method
A website with a password-protected settings page
A LED-control web page with live status updates
Getting started with ESPAsyncWebServer
The examples on this page were tested on an ESP32 WROOM module with ESPAsyncWebServer 3.12.1, AsyncTCP 3.5.0 and the Arduino-ESP32 3.3.12 platform.
At the beginning of the sketch, include WiFi.h together with AsyncTCP.h and ESPAsyncWebServer.h.
#include <WiFi.h>
#include <AsyncTCP.h>
#include <ESPAsyncWebServer.h>
Enter your Wi-Fi credentials:
const char* ssid = "mySSID";
const char* password = "myPassword";
Create an AsyncWebServer instance and specify the port on which it will listen. Port 80 is the default HTTP port.
AsyncWebServer server(80);
Start the serial connection in the setup() function.
Serial.begin(115200);
Connect to the Wi-Fi network in station mode. The sketch waits up to twenty seconds. If the connection fails, it restarts after a further five seconds. On success, it prints the ESP32’s IP address to the Serial Monitor.
WiFi.mode(WIFI_STA);
WiFi.begin(ssid, password);
Serial.print("Connecting to Wi-Fi");
const unsigned long deadline = millis() + 20000;
while (WiFi.status() != WL_CONNECTED && millis() < deadline)
{
delay(250);
Serial.print('.');
}
Serial.println();
if (WiFi.status() != WL_CONNECTED)
{
Serial.println("Wi-Fi connection timed out, restarting in 5 seconds.");
delay(5000);
ESP.restart();
}
Serial.println(WiFi.localIP());
An asynchronous web server can handle multiple connections. Each client request is represented by an AsyncWebServerRequest object. ESPAsyncWebServer handles requests in the background.
With server.on(), the first argument specifies the route that receives requests, and the second specifies the HTTP method, GET in this example. The third argument is a function that runs when a request arrives on that route.
The send() method of AsyncWebServerRequest defines the HTTP response. Here we send a simple string. Its three arguments are the HTTP status code 200, the content type “text/plain”, and the text to send, “Hello AsyncWebServer!”.
Finally, start the server with server.begin().
server.on("/hello_server", HTTP_GET, [](AsyncWebServerRequest *request)
{
request->send(200, "text/plain", "Hello AsyncWebServer!");
});
server.begin();
The loop() function remains empty because ESPAsyncWebServer does not require us to call a client-handling function there.
Here is the complete sketch:
#include <Arduino.h>
#include <WiFi.h>
#include <AsyncTCP.h>
#include <ESPAsyncWebServer.h>
const char* ssid = "mySSID";
const char* password = "myPassword";
AsyncWebServer server(80);
void setup()
{
Serial.begin(115200);
WiFi.mode(WIFI_STA);
WiFi.begin(ssid, password);
Serial.print("Connecting to Wi-Fi");
const unsigned long deadline = millis() + 20000;
while (WiFi.status() != WL_CONNECTED && millis() < deadline)
{
delay(250);
Serial.print('.');
}
Serial.println();
if (WiFi.status() != WL_CONNECTED)
{
Serial.println("Wi-Fi connection timed out, restarting in 5 seconds.");
delay(5000);
ESP.restart();
}
Serial.print("IP address: ");
Serial.println(WiFi.localIP());
server.on("/hello_server", HTTP_GET, [](AsyncWebServerRequest *request)
{
request->send(200, "text/plain", "Hello AsyncWebServer!");
});
server.begin();
}
void loop() {}
Compile and upload the sketch with the ESP32 WROOM Module board setting. Open the Serial Monitor at 115200 baud, then append the /hello_server route to the displayed IP address.
http://192.168.1.20/hello_server
You should see the response in the browser window.
Sending form data with the POST method
In the next example, we send text from an input field using POST and then display the submitted text.
#include <WiFi.h>
#include <AsyncTCP.h>
#include <ESPAsyncWebServer.h>
const char* ssid = "mySSID";
const char* password = "myPassword";
AsyncWebServer server(80);
const char* PARAM_MESSAGE = "message";
String postMessage = "";
const char index_html[] PROGMEM = R"rawliteral(
<!DOCTYPE HTML>
<html>
<head>
<title>ESP32 asynchronous web server</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<script>
function submitData()
{
setTimeout(function(){
document.location.reload(false);
}, 1000);
}
</script>
</head>
<body>
<center>
<h2>ESP32 asynchronous web server</h2>
<div style="height:50px"></div>
<p>HTTP POST message: %POST_MESSAGE%</p>
<form action="/post" method="POST" target="self_page">
<input type="text" name="message">
<br><br>
<input type="submit" value="Send..." onclick="submitData()">
</form>
</center>
<iframe style="display:none" name="self_page"></iframe>
</body>
</html> )rawliteral";
void notFound(AsyncWebServerRequest *request)
{
request->send(404, "text/plain", "Page not found");
}
String processor(const String& var)
{
if(var == "POST_MESSAGE")
{
return postMessage;
}
return String();
}
void setup()
{
Serial.begin(115200);
WiFi.begin(ssid, password);
Serial.print("Connecting to Wi-Fi.");
while (WiFi.status() != WL_CONNECTED)
{
delay(500);
Serial.print(".");
}
Serial.println();
Serial.println("Connected!");
Serial.print("IP address: ");
Serial.println(WiFi.localIP());
server.on("/", HTTP_GET, [](AsyncWebServerRequest *request)
{
request->send_P(200, "text/html", index_html, processor);
});
server.on("/post", HTTP_POST, [](AsyncWebServerRequest *request)
{
if(request->hasParam(PARAM_MESSAGE, true))
{
postMessage = request->getParam(PARAM_MESSAGE, true)->value();
}
request->send(200);
});
server.onNotFound(notFound);
server.begin();
}
void loop() {}
The HTML is stored in the constant character array “index_html[]”. PROGMEM tells the compiler to keep its contents in flash memory.
const char index_html[] PROGMEM = R"rawliteral(....)rawliteral";
The R prefix denotes a raw string literal: the text between the delimiters is taken as written. This example uses “rawliteral” as the delimiter, but another suitable delimiter could also be chosen.
If we enter an unknown address in the browser, notFound() handles the request. It sends HTTP status 404 with a plain-text response: “Page not found”.
void notFound(AsyncWebServerRequest *request)
{
request->send(404, "text/plain", "Page not found");
}
The HTML contains a placeholder enclosed in percent signs, %POST_MESSAGE%. When the page is sent, the processor() function replaces that placeholder with the matching text.
Here we change the content of a paragraph by supplying the value of the global postMessage variable for the %POST_MESSAGE% placeholder.
String postMessage = "";
<html>...
<p>HTTP POST message: %POST_MESSAGE%</p>
...</html>
String processor(const String& var)
{
if(var == "POST_MESSAGE")
{
return postMessage;
}
return String();
}
The first server.on() call serves the home page. Its route is simply “/”, so it handles requests to the ESP32’s IP address without an additional path.
send_P() returns HTTP status 200 and specifies the content type “text/html”. Its third argument is the HTML stored in index_html. Because the HTML has a placeholder, the fourth argument supplies the processor() function that replaces it.
server.on("/", HTTP_GET, [](AsyncWebServerRequest *request)
{
request->send_P(200, "text/html", index_html, processor);
});
The second server.on() call handles HTTP POST requests on the “/post” route. It checks whether the expected parameter is present and, if so, reads its value for further processing.
PARAM_MESSAGE identifies the text input named “message”. Its value is copied to the global postMessage variable. The handler then sends HTTP status 200.
const char* PARAM_MESSAGE = "message";
String postMessage = "";
</html>...
<input type="text" name="message">
...</html>
server.on("/post", HTTP_POST, [](AsyncWebServerRequest *request)
{
if(request->hasParam(PARAM_MESSAGE, true))
{
postMessage = request->getParam(PARAM_MESSAGE, true)->value();
}
request->send(200);
});
server.onNotFound(notFound) registers the notFound() function to handle requests for routes that do not exist.
server.onNotFound(notFound);
Finally, server.begin() starts AsyncWebServer.
server.begin();
Upload the sketch to the ESP32 and view the result in a web browser.

A website with a password-protected settings page
Security limitation:
The following sketch was verified on hardware, but it uses default credentials, unencrypted HTTP and state-changing GET requests.
Change the default credentials, test it only on a trusted, isolated local network, and do not expose it directly to the internet.
In the third example, we build a website with a home page and a settings page. It was tested again on an ESP32 WROOM module with Arduino-ESP32 3.3.12, ESPAsyncWebServer 3.12.1 and AsyncTCP 3.5.0.
If SPIFFS has not yet been initialized on your ESP32, setting FORMAT_SPIFFS_IF_FAILED to true allows the filesystem to be formatted when mounting fails. Formatting erases any files already stored there.
#define FORMAT_SPIFFS_IF_FAILED true
After SPIFFS mounts successfully, set this macro back to false. Otherwise a future mount failure could trigger formatting and erase stored settings.
On its first start, the ESP32 tries to connect to Wi-Fi but has no saved network credentials yet. After 15 seconds without a connection, it switches to access-point (AP) mode. Connect to the ESP32’s Wi-Fi access point.
The default connection details are:
SSID: Esp_AP
Password: 12345678
Important! The AP password must be at least eight characters long; otherwise the access point will not accept it.
After connecting to the ESP32 access point, open 192.168.7.22 in your browser.
On the home page, a line of text below the heading shows the LED state. Use the button beneath it to turn the LED on or off. The LED is connected to GPIO4 on the ESP32.
Farther down is a button that opens the settings page.

The settings page is password-protected. The default sign-in details are:
Username: admin
Password: admin.

The settings page contains two forms. In the first, we can enter or change the credentials for the Wi-Fi network and the access point (AP). Clicking Save stores them in SPIFFS (SPI Flash File Storage), a non-volatile area of flash memory.
The ESP32 then restarts.

The second form changes the credentials for the settings page. These are also stored in non-volatile memory. Saving them does not restart the ESP32.

Below the two forms are buttons for returning to the home page and signing out.

This sketch can be a useful starting point for projects that need editable settings. Here is the complete hardware-tested code.
#include <WiFi.h>
#include <ESPAsyncWebServer.h>
#include <AsyncTCP.h>
#include "FS.h"
#include "SPIFFS.h"
#define FORMAT_SPIFFS_IF_FAILED true
const char ledPin = 4;
String httpUsername = "admin";
String httpPassword = "admin";
String _AP_ssid = "Esp_AP";
String _AP_password = "12345678";
IPAddress local_IP(192,168,7,22);
IPAddress gateway(192,168,7,1);
IPAddress subnet(255,255,255,0);
AsyncWebServer server(80);
bool wifiIsConnected = false;
String ledValue ="false";
String ledState ="The LED is off!";
const char* param_ledvalue = "ledvalue";
const char* param_ap_ssid = "inputApSsid";
const char* param_ap_password = "inputApPassword";
const char* param_wifi_ssid = "inputWifiSsid";
const char* param_wifi_password = "inputWifiPassword";
const char* param_httpUsername = "inputHttpUsername";
const char* param_httpPassword = "inputHttpPassword";
const char index_html[] PROGMEM = R"rawliteral(
<!DOCTYPE HTML>
<html>
<head>
<title>Home page</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<script>
function submitData()
{
setTimeout(function(){
document.location.reload(false);
}, 1000);
}
</script>
</head>
<body>
<center>
<h2>ESP32 asynchronous web server</h2>
<div style="height:50px"></div>
<p>%LED_STATE%</p>
<form action="/ledSwitch" target="self_page">
<input type="hidden" name="ledvalue" value="%LED_VALUE%">
<input type="submit" value="LED" onclick="submitData()">
</form>
<br><br>
<button onclick="window.location.href='/settings';">Settings</button>
<iframe style="display:none" name="self_page"></iframe>
</center>
</body>
</html> )rawliteral";
const char settings_html[] PROGMEM = R"rawliteral(
<!DOCTYPE HTML>
<html>
<head>
<title>Settings</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<script>
function submitData()
{
setTimeout(function(){
document.location.reload(false);
}, 1000);
}
function logoutButton()
{
var xmlHttpRequest = new XMLHttpRequest();
xmlHttpRequest.open("GET", "/logout", true);
xmlHttpRequest.send();
setTimeout(function() {
window.open("/","/");
}, 1000);
}
</script>
</head>
<body>
<center>
<h2>Settings</h2>
<div style="height:50px"></div>
<fieldset style="width:300px">
<legend>Network settings:</legend>
<br><br>
<form action="/network" target="self_page">
AP SSID:<br>
<input type="text" value='%inputApSsid%' name="inputApSsid" size="20">
<br><br>
AP password:<br>
<input type="text" value='%inputApPassword%' name="inputApPassword" size="20">
<br>( At least 8 characters! )
<br><br>
Wi-Fi SSID:<br>
<input type="text" value='%inputWifiSsid%' name="inputWifiSsid" size="20">
<br><br>
Wi-Fi password:<br>
<input type="text" value='%inputWifiPassword%' name="inputWifiPassword" size="20">
<br><br>
<input type="submit" value="Save" onclick="submitData()">
</form>
<br><br>
</fieldset>
<div style="height:20px"></div>
<fieldset style="width:300px">
<legend>Login credentials:</legend>
<br><br>
<form action="/http_login_set" target="self_page">
Username:<br>
<input type="text" value='%inputHttpUsername%' name="inputHttpUsername" size="20">
<br><br>
Password:<br>
<input type="text" value='%inputHttpPassword%' name="inputHttpPassword" size="20">
<br><br><br>
<input type="submit" value="Save" onclick="submitData()">
</form>
<br><br>
</fieldset>
<div style="height:20px"></div>
<fieldset style="width:300px">
<legend>Back to home page</legend>
<br><br>
<button onclick="window.location.href='/';">Home page</button>
<br><br>
</fieldset>
<div style="height:20px"></div>
<fieldset style="width:300px">
<legend>Log out</legend>
<br><br>
<button onclick="logoutButton()">Log out</button>
<br><br>
</fieldset>
<div style="height:50px;"></div>
<iframe style="display:none" name="self_page"></iframe>
</center>
</body>
</html> )rawliteral";
String inputValueAdapter(const String& inputValueSet)
{
if(inputValueSet == "LED_STATE")
{
return ledState;
}
if(inputValueSet == "LED_VALUE")
{
return ledValue;
}
if(inputValueSet == "inputApSsid")
{
return readFile(SPIFFS, "/apSsid.txt");
}
if(inputValueSet == "inputApPassword")
{
return readFile(SPIFFS, "/apPassword.txt");
}
if(inputValueSet == "inputWifiSsid")
{
return readFile(SPIFFS, "/wifiSsid.txt");
}
if(inputValueSet == "inputWifiPassword")
{
return readFile(SPIFFS, "/wifiPassword.txt");
}
if(inputValueSet == "inputHttpUsername")
{
return readFile(SPIFFS, "/httpUsername.txt");
}
if(inputValueSet == "inputHttpPassword")
{
return readFile(SPIFFS, "/httpPassword.txt");
}
return String();
}
void setupAsyncServer()
{
server.on("/", HTTP_GET, [](AsyncWebServerRequest *request)
{
request->send_P(200, "text/html", index_html, inputValueAdapter);
});
server.on("/ledSwitch", HTTP_GET, [](AsyncWebServerRequest *request)
{
ledValue = request->getParam(param_ledvalue)->value();
if(ledValue == "true")
{
ledValue = "false";
digitalWrite(ledPin, LOW);
ledState ="The LED is off!";
}
else if(ledValue == "false")
{
ledValue = "true";
digitalWrite(ledPin, HIGH);
ledState ="The LED is on!";
}
request->send(200, "text/text", ledValue);
});
server.on("/settings", HTTP_GET, [](AsyncWebServerRequest *request)
{
String temp_httpUsername = readFile(SPIFFS, "/httpUsername.txt");
if(temp_httpUsername == "")
{
temp_httpUsername = httpUsername;
}
const char* http_username = temp_httpUsername.c_str();
String temp_httpPassword = readFile(SPIFFS, "/httpPassword.txt");
if(temp_httpPassword == "")
{
temp_httpPassword = httpPassword;
}
const char* http_password = temp_httpPassword.c_str();
if(!request->authenticate(http_username, http_password))
{
return request->requestAuthentication();
}
request->send_P(200, "text/html", settings_html, inputValueAdapter);
});
server.on("/network", HTTP_GET, [](AsyncWebServerRequest *request)
{
String temp_httpUsername = readFile(SPIFFS, "/httpUsername.txt");
if(temp_httpUsername == "")
{
temp_httpUsername = httpUsername;
}
const char* http_username = temp_httpUsername.c_str();
String temp_httpPassword = readFile(SPIFFS, "/httpPassword.txt");
if(temp_httpPassword == "")
{
temp_httpPassword = httpPassword;
}
const char* http_password = temp_httpPassword.c_str();
if(!request->authenticate(http_username, http_password))
{
return request->requestAuthentication();
}
String inputMessage;
if (request->hasParam(param_ap_ssid))
{
inputMessage = request->getParam(param_ap_ssid)->value();
writeFile(SPIFFS, "/apSsid.txt", inputMessage.c_str());
}
if (request->hasParam(param_ap_password))
{
inputMessage = request->getParam(param_ap_password)->value();
writeFile(SPIFFS, "/apPassword.txt", inputMessage.c_str());
}
if (request->hasParam(param_wifi_ssid))
{
inputMessage = request->getParam(param_wifi_ssid)->value();
writeFile(SPIFFS, "/wifiSsid.txt", inputMessage.c_str());
}
if (request->hasParam(param_wifi_password))
{
inputMessage = request->getParam(param_wifi_password)->value();
writeFile(SPIFFS, "/wifiPassword.txt", inputMessage.c_str());
}
request->send(200, "text/text", inputMessage);
Serial.println("ESP Restart...");
ESP.restart();
});
server.on("/http_login_set", HTTP_GET, [](AsyncWebServerRequest *request)
{
String temp_httpUsername = readFile(SPIFFS, "/httpUsername.txt");
if(temp_httpUsername == "")
{
temp_httpUsername = httpUsername;
}
const char* http_username = temp_httpUsername.c_str();
String temp_httpPassword = readFile(SPIFFS, "/httpPassword.txt");
if(temp_httpPassword == "")
{
temp_httpPassword = httpPassword;
}
const char* http_password = temp_httpPassword.c_str();
if(!request->authenticate(http_username, http_password))
{
return request->requestAuthentication();
}
String inputMessage;
if (request->hasParam(param_httpUsername))
{
inputMessage = request->getParam(param_httpUsername)->value();
writeFile(SPIFFS, "/httpUsername.txt", inputMessage.c_str());
}
if (request->hasParam(param_httpPassword))
{
inputMessage = request->getParam(param_httpPassword)->value();
writeFile(SPIFFS, "/httpPassword.txt", inputMessage.c_str());
}
request->send(200, "text/text", inputMessage);
});
server.on("/logout", HTTP_GET, [](AsyncWebServerRequest *request)
{
request->send(401);
});
server.onNotFound(notFound);
server.begin();
}
void notFound(AsyncWebServerRequest *request)
{
request->send(404, "text/plain", "Page not found");
}
String readFile(fs::FS &fs, const char * path)
{
String fileContent = "";
File file = fs.open(path, "r");
if(!file || file.isDirectory())
{
return fileContent;
}
while(file.available())
{
fileContent+=String((char)file.read());
}
file.close();
return fileContent;
}
void writeFile(fs::FS &fs, const char * path, const char * message)
{
File file = fs.open(path, "w");
if(!file)
{
return;
}
file.print(message);
file.close();
}
void setup_ap()
{
String temp_pass = readFile(SPIFFS, "/apPassword.txt");
if(temp_pass == "")
{
temp_pass = _AP_password;
}
String temp_ssid = readFile(SPIFFS, "/apSsid.txt");
if(temp_ssid == "")
{
temp_ssid = _AP_ssid;
}
const char* AP_ssid = temp_ssid.c_str();
const char* AP_password = temp_pass.c_str();
WiFi.softAPConfig(local_IP, gateway, subnet);
WiFi.softAP(AP_ssid, AP_password);
IPAddress Ap_Ip = WiFi.softAPIP();
Serial.print("Access point IP address: ");
Serial.println(Ap_Ip);
Serial.println();
}
void setup_wifi()
{
String temp_pass = readFile(SPIFFS, "/wifiPassword.txt");
char passbuff[temp_pass.length() + 1];
temp_pass.toCharArray(passbuff, temp_pass.length() + 1);
const char* password = passbuff;
String temp_ssid = readFile(SPIFFS, "/wifiSsid.txt");
char ssidbuff[temp_ssid.length() + 1];
temp_ssid.toCharArray(ssidbuff, temp_ssid.length() + 1);
const char* ssid = ssidbuff;
WiFi.begin(ssid, password);
Serial.print("Connecting to Wi-Fi.");
int i = 0;
while (true)
{
if(WiFi.status() != WL_CONNECTED)
{
delay(500);
Serial.print(".");
i++;
if(i > 30)
{
wifiIsConnected = false;
Serial.println();
Serial.println("Could not connect to Wi-Fi.");
break;
}
}
else
{
wifiIsConnected = true;
Serial.println();
Serial.println("Connected!");
Serial.print("IP address: ");
Serial.println(WiFi.localIP());
Serial.println();
break;
}
}
}
void setup()
{
pinMode(ledPin, OUTPUT);
digitalWrite(ledPin, HIGH);
delay(2000);
digitalWrite(ledPin, LOW);
Serial.begin(115200);
SPIFFS.begin(FORMAT_SPIFFS_IF_FAILED);
WiFi.mode(WIFI_STA);
setup_wifi();
if(!wifiIsConnected)
{
WiFi.mode(WIFI_AP);
setup_ap();
}
setupAsyncServer();
}
void loop(){}
A LED-control web page with live status updates
In the next example, we create an asynchronous web server on an ESP32 WROOM module. Buttons in the browser control an LED connected to GPIO4.
The web page sends a request, and the ESP32 responds with the current state of GPIO4. The browser uses that response to display whether the LED is on or off.
#include <Arduino.h>
#include <WiFi.h>
#include <AsyncTCP.h>
#include <ESPAsyncWebServer.h>
constexpr char ssid[] = "mySSID";
constexpr char password[] = "myPassword";
namespace {
constexpr uint8_t LED_PIN = 4;
AsyncWebServer server(80);
const char INDEX_HTML[] PROGMEM = R"HTML(<!doctype html>
<html lang="en">
<meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
<title>ESP32 asynchronous web server</title>
<style>body{font:1rem system-ui;max-width:42rem;margin:3rem auto;padding:0 1rem}button{font:inherit;padding:.7rem 1rem}</style>
<h1>ESP32 asynchronous web server</h1><p id="state">Loading…</p>
<button onclick="setLed(true)">LED on</button> <button onclick="setLed(false)">LED off</button>
<script>
async function refresh(){
const r=await fetch('/api/status');
if(!r.ok)throw Error(r.status);
const d=await r.json();
state.textContent='LED: '+(d.led?'on':'off')
}
async function setLed(on){
const r=await fetch('/api/led',{method:'POST',headers:{'Content-Type':'application/x-www-form-urlencoded'},body:'state='+(on?'on':'off')});
if(!r.ok)alert(await r.text());
await refresh()
}
refresh().catch(e=>state.textContent='Request failed: '+e.message);
</script>
</html>)HTML";
void sendStatus(AsyncWebServerRequest *request)
{
const bool on = digitalRead(LED_PIN) == HIGH;
request->send(200, "application/json", on ? "{\"led\":true}" : "{\"led\":false}");
}
void connectWiFi()
{
WiFi.mode(WIFI_STA);
WiFi.begin(ssid, password);
Serial.print("Connecting to Wi-Fi");
const unsigned long deadline = millis() + 20000;
while (WiFi.status() != WL_CONNECTED && millis() < deadline)
{
delay(250);
Serial.print('.');
}
Serial.println();
if(WiFi.status() != WL_CONNECTED)
{
Serial.println("Wi-Fi connection timed out, restarting in 5 seconds.");
delay(5000);
ESP.restart();
}
Serial.print("Open http://");
Serial.println(WiFi.localIP());
}
}
void setup()
{
Serial.begin(115200);
pinMode(LED_PIN, OUTPUT);
digitalWrite(LED_PIN, LOW);
connectWiFi();
server.on("/", HTTP_GET, [](AsyncWebServerRequest *request)
{
request->send(200, "text/html", INDEX_HTML);
});
server.on("/api/status", HTTP_GET, sendStatus);
server.on("/api/led", HTTP_POST, [](AsyncWebServerRequest *request)
{
if(!request->hasParam("state", true)) return request->send(400, "text/plain", "Missing state");
const String value = request->getParam("state", true)->value();
if (value != "on" && value != "off") return request->send(422, "text/plain", "state must be on or off");
digitalWrite(LED_PIN, value == "on" ? HIGH : LOW);
request->send(204);
});
server.onNotFound([](AsyncWebServerRequest *request) { request->send(404, "text/plain", "Not found"); });
server.begin();
}
void loop() {}
How does the code work?
The easiest way to understand this project is to follow what happens from powering on the ESP32 to pressing the first button. Rather than explaining every line in isolation, we will look at the sequence of events.
First, include the required libraries and enter the credentials for your own Wi-Fi network.
#include <Arduino.h>
#include <WiFi.h>
#include <AsyncTCP.h>
#include <ESPAsyncWebServer.h>
constexpr char ssid[] = "mySSID";
constexpr char password[] = "myPassword";
LED_PIN identifies GPIO4, where the LED is connected. We also create an asynchronous web server on port 80.
constexpr uint8_t LED_PIN = 4;
AsyncWebServer server(80);
The INDEX_HTML character array contains the web page shown in the browser. PROGMEM keeps this relatively large text in flash memory rather than occupying scarce RAM.
const char INDEX_HTML[] PROGMEM = R"HTML(<!doctype html>
<html lang="en">.....
In setup(), we start the Serial Monitor at 115200 baud. We configure GPIO4 as an output and set it LOW, turning the LED off. Then we call connectWiFi().
void setup()
{
Serial.begin(115200);
pinMode(LED_PIN, OUTPUT);
digitalWrite(LED_PIN, LOW);
connectWiFi();
.....
connectWiFi() tries to join the local Wi-Fi network in station mode. It waits no more than twenty seconds. If the connection fails, it waits five more seconds and restarts the ESP32.
void connectWiFi()
{
WiFi.mode(WIFI_STA);
WiFi.begin(ssid, password);
Serial.print("Connecting to Wi-Fi");
const unsigned long deadline = millis() + 20000;
while (WiFi.status() != WL_CONNECTED && millis() < deadline)
{
delay(250);
Serial.print('.');
}
Serial.println();
if(WiFi.status() != WL_CONNECTED)
{
Serial.println("Wi-Fi connection timed out, restarting in 5 seconds.");
delay(5000);
ESP.restart();
}
Serial.print("Open http://");
Serial.println(WiFi.localIP());
}
After a successful connection, the IP address is printed to the Serial Monitor. We will enter this address in the browser.
Once Wi-Fi is connected, setup() continues. The sketch registers routes for the home page, status requests, LED control and unknown addresses.
The server.begin() call then starts the web server.
void setup()
{
....
server.on("/", HTTP_GET, [](AsyncWebServerRequest *request)
{
request->send(200, "text/html", INDEX_HTML);
});
server.on("/api/status", HTTP_GET, sendStatus);
server.on("/api/led", HTTP_POST, [](AsyncWebServerRequest *request)
{
if(!request->hasParam("state", true)) return request->send(400, "text/plain", "Missing state");
const String value = request->getParam("state", true)->value();
if (value != "on" && value != "off") return request->send(422, "text/plain", "state must be on or off");
digitalWrite(LED_PIN, value == "on" ? HIGH : LOW);
request->send(204);
});
server.onNotFound([](AsyncWebServerRequest *request) { request->send(404, "text/plain", "Not found"); });
server.begin();
}
void loop() {}
You may have noticed that loop() is empty. ESPAsyncWebServer handles network requests asynchronously, so no client-handling call is needed in the loop. You can use loop() for other tasks, such as reading sensors or updating a display, but long blocking operations can still affect responsiveness.
When we open the ESP32’s IP address, the browser requests the / route. The server responds with the page stored in the sketch as INDEX_HTML.
server.on("/", HTTP_GET, [](AsyncWebServerRequest *request)
{
request->send(200, "text/html", INDEX_HTML);
});
As soon as the home page loads, the browser calls refresh(), which sends a GET /api/status request.
<script>
async function refresh(){
const r=await fetch('/api/status');
if(!r.ok)throw Error(r.status);
const d=await r.json();
state.textContent='LED: '+(d.led?'on':'off')
}
The server receives this request and calls sendStatus().
server.on("/api/status", HTTP_GET, sendStatus);
The ESP32 builds a JSON response from the current state of GPIO4.
void sendStatus(AsyncWebServerRequest *request)
{
const bool on = digitalRead(LED_PIN) == HIGH;
request->send(200, "application/json", on ? "{\"led\":true}" : "{\"led\":false}");
}
The browser’s refresh() function reads that JSON response.
<script>
async function refresh(){
const r=await fetch('/api/status');
if(!r.ok)throw Error(r.status);
const d=await r.json();
state.textContent='LED: '+(d.led?'on':'off')
}
It then changes the text of the element with id="state" to show whether the LED is on or off.
<p id="state">Loading…</p>
The entire page does not reload; only the visible status text changes.
Pressing the “LED on” button calls setLed(true). Pressing “LED off” calls setLed(false).
<button onclick="setLed(true)">LED on</button>
<button onclick="setLed(false)">LED off</button>
When either button is pressed, setLed() sends a POST request to /api/led. The “LED on” button sends state=on, while “LED off” sends state=off.
async function setLed(on){
const r=await fetch('/api/led',{method:'POST',headers:{'Content-Type':'application/x-www-form-urlencoded'},body:'state='+(on?'on':'off')});
if(!r.ok)alert(await r.text());
await refresh()
}
refresh().catch(e=>state.textContent='Request failed: '+e.message);
</script>
The server first checks that the state parameter is present and that its value is one of the two allowed choices. A missing value returns HTTP 400; an invalid one returns HTTP 422. Neither changes the LED. For a valid request, the server sets GPIO4 and returns HTTP 204.
server.on("/api/led", HTTP_POST, [](AsyncWebServerRequest *request)
{
if(!request->hasParam("state", true)) return request->send(400, "text/plain", "Missing state");
const String value = request->getParam("state", true)->value();
if (value != "on" && value != "off") return request->send(422, "text/plain", "state must be on or off");
digitalWrite(LED_PIN, value == "on" ? HIGH : LOW);
request->send(204);
});
The browser then calls refresh() again. It does not infer the displayed state solely from the button pressed; it asks the ESP32 for the current state. This happens when the page opens and after a button press. There is no continuous background polling.
If we request an unknown route, the sketch returns HTTP 404.
server.onNotFound([](AsyncWebServerRequest *request) { request->send(404, "text/plain", "Not found"); });
These small checks show how receiving a request, validating its data and changing a hardware output are separate steps.
