ESP32 WebSocket Server: Control Outputs (Arduino IDE)

In this tutorial you’ll learn how to build a web server with the ESP32 using WebSocket communication protocol. As an example, we’ll show you how to build a web page to control the ESP32 outputs remotely. The output state is displayed on the web page and it updates automatically in all clients.

ESP32 WebSocket Server Control Outputs Arduino IDE

The ESP32 will be programmed using Arduino IDE and the ESPAsyncWebServer. We also have a similar WebSocket guide for the ESP8266.

If you’ve been following some of our previous web server projects like this one, you may have noticed that if you have several tabs (in the same or on different devices) opened at the same time, the state doesn’t update in all tabs automatically unless you refresh the web page. To solve this issue, we can use WebSocket protocol – all clients can be notified when a change occurs and update the web page accordingly.

This tutorial was based on a project created and documented by one of our readers (Stéphane Calderoni). You can read his excellent tutorial here.

Introducing WebSocket

A WebSocket is a persistent connection between a client and a server that allows bidirectional communication between both parties using a TCP connection. This means you can send data from the client to the server and from the server to the client at any given time. 

ESP32 ESP8266 WebSocket Server How it Works

The client establishes a WebSocket connection with the server through a process known as WebSocket handshake. The handshake starts with an HTTP request/response, allowing servers to handle HTTP connections as well as WebSocket connections on the same port. Once the connection is established, the client and the server can send WebSocket data in full duplex mode.

Using the WebSockets protocol, the server (ESP32 board) can send information to the client or to all clients without being requested. This also allows us to send information to the web browser when a change occurs.

This change can be something that happened on the web page (you clicked a button) or something that happened on the ESP32 side like pressing a physical button on a circuit.

Project Overview

Here’s the web page we’ll build for this project.

ESP32 WebSocket Server Toggle Outputs Project Overview
  • The ESP32 web server displays a web page with a button to toggle the state of GPIO 2;
  • For simplicity, we’re controlling GPIO 2 – the on-board LED. You can use this example to control any other GPIO;
  • The interface shows the current GPIO state. Whenever a change occurs on the GPIO state, the interface is updated instantaneously;
  • The GPIO state is updated automatically in all clients. This means that if you have several web browser tabs opened on the same device or on different devices, they are all updated at the same time.

How it Works?

The following image describes what happens when click on the “Toggle” button.

ESP32 WebSocket Web Server Update All Clients How it Works

Here’s what happens when you click on the “Toggle” button:

  1. Click on the “Toggle” button;
  2. The client (your browser) sends data via WebSocket protocol with the “toggle” message;
  3. The ESP32 (server) receives this message, so it knows it should toggle the LED state. If the LED was previously off, turn it on;
  4. Then, it sends data with the new LED state to all clients also through WebSocket protocol;
  5. The clients receive the message and update the led state on the web page accordingly. This allows us to update all clients almost instantaneously when a change happens.

Preparing Arduino IDE

We’ll program the ESP32 board using Arduino IDE, so make sure you have it installed in your Arduino IDE.

Installing Libraries – Async Web Server

To build the web server we’ll use the ESPAsyncWebServer library. This library needs the AsyncTCP library to work properly. 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.

Code for ESP32 WebSocket Server

Copy the following code to your Arduino IDE.

/*********
  Rui Santos
  Complete project details at https://RandomNerdTutorials.com/esp32-websocket-server-arduino/
  The above copyright notice and this permission notice shall be included in all
  copies or substantial portions of the Software.
*********/

// Import required libraries
#include <WiFi.h>
#include <AsyncTCP.h>
#include <ESPAsyncWebServer.h>

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

bool ledState = 0;
const int ledPin = 2;

// Create AsyncWebServer object on port 80
AsyncWebServer server(80);
AsyncWebSocket ws("/ws");

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, Helvetica, sans-serif;
    text-align: center;
  }
  h1 {
    font-size: 1.8rem;
    color: white;
  }
  h2{
    font-size: 1.5rem;
    font-weight: bold;
    color: #143642;
  }
  .topnav {
    overflow: hidden;
    background-color: #143642;
  }
  body {
    margin: 0;
  }
  .content {
    padding: 30px;
    max-width: 600px;
    margin: 0 auto;
  }
  .card {
    background-color: #F8F7F9;;
    box-shadow: 2px 2px 12px 1px rgba(140,140,140,.5);
    padding-top:10px;
    padding-bottom:20px;
  }
  .button {
    padding: 15px 50px;
    font-size: 24px;
    text-align: center;
    outline: none;
    color: #fff;
    background-color: #0f8b8d;
    border: none;
    border-radius: 5px;
    -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: #0f8b8d}*/
   .button:active {
     background-color: #0f8b8d;
     box-shadow: 2 2px #CDCDCD;
     transform: translateY(2px);
   }
   .state {
     font-size: 1.5rem;
     color:#8c8c8c;
     font-weight: bold;
   }
  </style>
<title>ESP Web Server</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="icon" href="data:,">
</head>
<body>
  <div class="topnav">
    <h1>ESP WebSocket Server</h1>
  </div>
  <div class="content">
    <div class="card">
      <h2>Output - GPIO 2</h2>
      <p class="state">state: <span id="state">%STATE%</span></p>
      <p><button id="button" class="button">Toggle</button></p>
    </div>
  </div>
<script>
  var gateway = `ws://${window.location.hostname}/ws`;
  var websocket;
  window.addEventListener('load', onLoad);
  function initWebSocket() {
    console.log('Trying to open a WebSocket connection...');
    websocket = new WebSocket(gateway);
    websocket.onopen    = onOpen;
    websocket.onclose   = onClose;
    websocket.onmessage = onMessage; // <-- add this line
  }
  function onOpen(event) {
    console.log('Connection opened');
  }
  function onClose(event) {
    console.log('Connection closed');
    setTimeout(initWebSocket, 2000);
  }
  function onMessage(event) {
    var state;
    if (event.data == "1"){
      state = "ON";
    }
    else{
      state = "OFF";
    }
    document.getElementById('state').innerHTML = state;
  }
  function onLoad(event) {
    initWebSocket();
    initButton();
  }
  function initButton() {
    document.getElementById('button').addEventListener('click', toggle);
  }
  function toggle(){
    websocket.send('toggle');
  }
</script>
</body>
</html>
)rawliteral";

void notifyClients() {
  ws.textAll(String(ledState));
}

void handleWebSocketMessage(void *arg, uint8_t *data, size_t len) {
  AwsFrameInfo *info = (AwsFrameInfo*)arg;
  if (info->final && info->index == 0 && info->len == len && info->opcode == WS_TEXT) {
    data[len] = 0;
    if (strcmp((char*)data, "toggle") == 0) {
      ledState = !ledState;
      notifyClients();
    }
  }
}

void onEvent(AsyncWebSocket *server, AsyncWebSocketClient *client, AwsEventType type,
             void *arg, uint8_t *data, size_t len) {
  switch (type) {
    case WS_EVT_CONNECT:
      Serial.printf("WebSocket client #%u connected from %s\n", client->id(), client->remoteIP().toString().c_str());
      break;
    case WS_EVT_DISCONNECT:
      Serial.printf("WebSocket client #%u disconnected\n", client->id());
      break;
    case WS_EVT_DATA:
      handleWebSocketMessage(arg, data, len);
      break;
    case WS_EVT_PONG:
    case WS_EVT_ERROR:
      break;
  }
}

void initWebSocket() {
  ws.onEvent(onEvent);
  server.addHandler(&ws);
}

String processor(const String& var){
  Serial.println(var);
  if(var == "STATE"){
    if (ledState){
      return "ON";
    }
    else{
      return "OFF";
    }
  }
}

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

  pinMode(ledPin, OUTPUT);
  digitalWrite(ledPin, 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());

  initWebSocket();

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

  // Start server
  server.begin();
}

void loop() {
  ws.cleanupClients();
  digitalWrite(ledPin, ledState);
}

View raw code

Insert your network credentials in the following variables and the code will work straight away.

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

How the Code Works

Continue reading to learn how the code works or skip to the Demonstration section.

Importing Libraries

Import the necessary libraries to build the web server.

#include <WiFi.h>
#include <AsyncTCP.h>
#include <ESPAsyncWebServer.h>

Network Credentials

Insert your network credentials in the following variables:

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

GPIO Output

Create a variable called ledState to hold the GPIO state and a variable called ledPin that refers to the GPIO you want to control. In this case, we’ll control the on-board LED (that is connected to GPIO 2).

bool ledState = 0;
const int ledPin = 2;

AsyncWebServer and AsyncWebSocket

Create an AsyncWebServer object on port 80.

AsyncWebServer server(80);

The ESPAsyncWebServer library includes a WebSocket plugin that makes it easy to handle WebSocket connections. Create an AsyncWebSocket object called ws to handle the connections on the /ws path.

AsyncWebSocket ws("/ws");

Building the Web Page

The index_html variable contains the HTML, CSS and JavaScript needed to build and style the web page and handle client-server interactions using WebSocket protocol.

Note: we’re placing everything needed to build the web page on the index_html variable that we use on the Arduino sketch. Note that it may be more practical to have separated HTML, CSS and JavaScript files that then you upload to the ESP32 filesystem and reference them on the code.

Recommended reading: ESP32 Web Server using SPIFFS (SPI Flash File System)

Here’s the content of the index_html variable:

<!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, Helvetica, sans-serif;
    text-align: center;
  }
  h1 {
    font-size: 1.8rem;
    color: white;
  }
  h2{
    font-size: 1.5rem;
    font-weight: bold;
    color: #143642;
  }
  .topnav {
    overflow: hidden;
    background-color: #143642;
  }
  body {
    margin: 0;
  }
  .content {
    padding: 30px;
    max-width: 600px;
    margin: 0 auto;
  }
  .card {
    background-color: #F8F7F9;;
    box-shadow: 2px 2px 12px 1px rgba(140,140,140,.5);
    padding-top:10px;
    padding-bottom:20px;
  }
  .button {
    padding: 15px 50px;
    font-size: 24px;
    text-align: center;
    outline: none;
    color: #fff;
    background-color: #0f8b8d;
    border: none;
    border-radius: 5px;
    -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:active {
     background-color: #0f8b8d;
     box-shadow: 2 2px #CDCDCD;
     transform: translateY(2px);
   }
   .state {
     font-size: 1.5rem;
     color:#8c8c8c;
     font-weight: bold;
   }
  </style>
<title>ESP Web Server</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="icon" href="data:,">
</head>
<body>
  <div class="topnav">
    <h1>ESP WebSocket Server</h1>
  </div>
  <div class="content">
    <div class="card">
      <h2>Output - GPIO 2</h2>
      <p class="state">state: <span id="state">%STATE%</span></p>
      <p><button id="button" class="button">Toggle</button></p>
    </div>
  </div>
<script>
  var gateway = `ws://${window.location.hostname}/ws`;
  var websocket;
  function initWebSocket() {
    console.log('Trying to open a WebSocket connection...');
    websocket = new WebSocket(gateway);
    websocket.onopen    = onOpen;
    websocket.onclose   = onClose;
    websocket.onmessage = onMessage; // <-- add this line
  }
  function onOpen(event) {
    console.log('Connection opened');
  }

  function onClose(event) {
    console.log('Connection closed');
    setTimeout(initWebSocket, 2000);
  }
  function onMessage(event) {
    var state;
    if (event.data == "1"){
      state = "ON";
    }
    else{
      state = "OFF";
    }
    document.getElementById('state').innerHTML = state;
  }
  window.addEventListener('load', onLoad);
  function onLoad(event) {
    initWebSocket();
    initButton();
  }

  function initButton() {
    document.getElementById('button').addEventListener('click', toggle);
  }
  function toggle(){
    websocket.send('toggle');
  }
</script>
</body>
</html>

CSS

Between the <style> </style> tags we include the styles to style the web page using CSS. Feel free to change it to make the web page look as you wish. We won’t explain how the CSS for this web page works because it is not relevant for this WebSocket tutorial.

<style>
  html {
    font-family: Arial, Helvetica, sans-serif;
    text-align: center;
  }
  h1 {
    font-size: 1.8rem;
    color: white;
  }
  h2 {
    font-size: 1.5rem;
    font-weight: bold;
    color: #143642;
  }
  .topnav {
    overflow: hidden;
    background-color: #143642;
  }
  body {
    margin: 0;
  }
  .content {
    padding: 30px;
    max-width: 600px;
    margin: 0 auto;
  }
  .card {
    background-color: #F8F7F9;;
    box-shadow: 2px 2px 12px 1px rgba(140,140,140,.5);
    padding-top:10px;
    padding-bottom:20px;
  }
  .button {
    padding: 15px 50px;
    font-size: 24px;
    text-align: center;
    outline: none;
    color: #fff;
    background-color: #0f8b8d;
    border: none;
    border-radius: 5px;
    -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:active {
     background-color: #0f8b8d;
     box-shadow: 2 2px #CDCDCD;
     transform: translateY(2px);
   }
   .state {
     font-size: 1.5rem;
     color:#8c8c8c;
     font-weight: bold;
   }
 </style>

HTML

Between the <body> </body> tags we add the web page content that is visible to the user.

<div class="topnav">
  <h1>ESP WebSocket Server</h1>
</div>
<div class="content">
  <div class="card">
    <h2>Output - GPIO 2</h2>
    <p class="state">state: <span id="state">%STATE%</span></p>
    <p><button id="button" class="button">Toggle</button></p>
  </div>
</div>

There’s a heading 1 with the text “ESP WebSocket Server”. Feel free to modify that text.

<h1>ESP WebSocket Server</h1>

Then, there’s a heading 2 with the “Output – GPIO 2” text.

<h2>Output - GPIO 2</h2>

After that, we have a paragraph that displays the current GPIO state.

<p class="state">state: <span id="state">%STATE%</span></p>

The %STATE% is a placeholder for the GPIO state. It will be replaced with the current value by the ESP32 at the time of sending the web page. The placeholders on the HTML text should go between % signs. This means that this %STATE% text is like a variable that will then be replaced with the actual value.

After sending the web page to the client, the state needs to change dynamically whenever there’s a change in the GPIO state. We’ll receive that information via WebSocket protocol. Then, JavaScript handles what to do with the information received to update the state accordingly. To be able to handle that text using JavaScript, the text must have an id that we can reference. In this case the id is state ( <span id=”state”>).

Finally, there’s a paragraph with the button to toggle the GPIO state.

<p><button id="button" class="button">Toggle</button></p>

Note that we’ve given an id to the button ( id=”button”).

JavaScript – Handling WebSockets

The JavaScript goes between the <script> </script> tags. It is responsible for initializing a WebSocket connection with the server as soon the web interface is fully loaded in the browser and handling data exchange through WebSockets.

<script>
  var gateway = `ws://${window.location.hostname}/ws`;
  var websocket;
  function initWebSocket() {
    console.log('Trying to open a WebSocket connection...');
    websocket = new WebSocket(gateway);
    websocket.onopen    = onOpen;
    websocket.onclose   = onClose;
    websocket.onmessage = onMessage; // <-- add this line
  }
  function onOpen(event) {
    console.log('Connection opened');
  }

  function onClose(event) {
    console.log('Connection closed');
    setTimeout(initWebSocket, 2000);
  }
  function onMessage(event) {
    var state;
    if (event.data == "1"){
      state = "ON";
    }
    else{
      state = "OFF";
    }
    document.getElementById('state').innerHTML = state;
  }

  window.addEventListener('load', onLoad);

  function onLoad(event) {
    initWebSocket();
    initButton();
  }

  function initButton() {
    document.getElementById('button').addEventListener('click', toggle);
  }

  function toggle(){
    websocket.send('toggle');
  }
</script>

Let’s take a look at how this works.

The gateway is the entry point to the WebSocket interface.

var gateway = `ws://${window.location.hostname}/ws`;

window.location.hostname gets the current page address (the web server IP address).

Create a new global variable called websocket.

var websocket;

Add an event listener that will call the onload function when the web page loads.

window.addEventListener('load', onload);

The onload() function calls the initWebSocket() function to initialize a WebSocket connection with the server and the initButton() function to add event listeners to the buttons.

function onload(event) {
  initWebSocket();
  initButton();
}

The initWebSocket() function initializes a WebSocket connection on the gateway defined earlier. We also assign several callback functions for when the WebSocket connection is opened, closed or when a message is received.

function initWebSocket() {
  console.log('Trying to open a WebSocket connection…');
  websocket = new WebSocket(gateway);
  websocket.onopen    = onOpen;
  websocket.onclose   = onClose;
  websocket.onmessage = onMessage;
}

When the connection is opened, we simply print a message in the console and send a message saying “hi”. The ESP32 receives that message, so we know that the connection was initialized.

function onOpen(event) {
  console.log('Connection opened');
  websocket.send('hi');
}

If for some reason the web socket connection is closed, we call the initWebSocket() function again after 2000 milliseconds (2 seconds).

function onClose(event) {
  console.log('Connection closed');
  setTimeout(initWebSocket, 2000);
} 

The setTimeout() method calls a function or evaluates an expression after a specified number of milliseconds.

Finally, we need to handle what happens  when we receive a new message. The server (your ESP board) will either send a “1” or a “0” message. Accordingly to the received message, we want to display an “ON” or a “OFF” message on the paragraph that displays the state. Remember that <span> tag with id=”state”? We’ll get that element and set its value to ON or OFF.

function onMessage(event) {
  var state;
  if (event.data == "1"){
    state = "ON";
  }
  else{
    state = "OFF";
  }
  document.getElementById('state').innerHTML = state;
}

The initButton() function gets the button by its id (button) and adds an event listener of type ‘click’.

function initButton() {
  document.getElementById('button').addEventListener('click', toggle);
}

This means that when you click the button, the toggle function is called.

The toggle function sends a message using the WebSocket connection with the ‘toggle’ text.

function toggle(){
  websocket.send('toggle');
}

Then, the ESP32 should handle what happens when it receives this message – toggle the current GPIO state.

Handling WebSockets – Server

Previously, you’ve seen how to handle the WebSocket connection on the client side (browser). Now, let’s take a look on how to handle it on the server side.

Notify All Clients

The notifyClients() function notifies all clients with a message containing whatever you pass as a argument. In this case, we’ll want to notify all clients of the current LED state whenever there’s a change.

void notifyClients() {
  ws.textAll(String(ledState));
}

The AsyncWebSocket class provides a textAll() method for sending the same message to all clients that are connected to the server at the same time.

Handle WebSocket Messages

The handleWebSocketMessage() function is a callback function that will run whenever we receive new data from the clients via WebSocket protocol.

void handleWebSocketMessage(void *arg, uint8_t *data, size_t len) {
  AwsFrameInfo *info = (AwsFrameInfo*)arg;
  if (info->final && info->index == 0 && info->len == len && info->opcode == WS_TEXT) {
    data[len] = 0;
    if (strcmp((char*)data, "toggle") == 0) {
      ledState = !ledState;
      notifyClients();
    }
  }
}

If we receive the “toggle” message, we toggle the value of the ledState variable. Additionally, we notify all clients by calling the notifyClients() function. This way, all clients are notified of the change and update the interface accordingly.

if (strcmp((char*)data, "toggle") == 0) {
  ledState = !ledState;
  notifyClients();
}

Configure the WebSocket server

Now we need to configure an event listener to handle the different asynchronous steps of the WebSocket protocol. This event handler can be implemented by defining the onEvent() as follows:

void onEvent(AsyncWebSocket *server, AsyncWebSocketClient *client, AwsEventType type,
 void *arg, uint8_t *data, size_t len) {
  switch (type) {
    case WS_EVT_CONNECT:
      Serial.printf("WebSocket client #%u connected from %s\n", client->id(), client->remoteIP().toString().c_str());
      break;
    case WS_EVT_DISCONNECT:
      Serial.printf("WebSocket client #%u disconnected\n", client->id());
      break;
    case WS_EVT_DATA:
      handleWebSocketMessage(arg, data, len);
      break;
    case WS_EVT_PONG:
    case WS_EVT_ERROR:
      break;
  }
}

The type argument represents the event that occurs. It can take the following values:

  • WS_EVT_CONNECT when a client has logged in;
  • WS_EVT_DISCONNECT when a client has logged out;
  • WS_EVT_DATA when a data packet is received from the client;
  • WS_EVT_PONG in response to a ping request;
  • WS_EVT_ERROR when an error is received from the client.

Initialize WebSocket

Finally, the initWebSocket() function initializes the WebSocket protocol.

void initWebSocket() {
  ws.onEvent(onEvent);
  server.addHandler(&ws);
}

processor()

The processor() function is responsible for searching for placeholders on the HTML text and replace them with whatever we want before sending the web page to the browser. In our case, we’ll replace the %STATE% placeholder with ON if the ledState is 1. Otherwise, replace it with OFF.

String processor(const String& var){
  Serial.println(var);
  if(var == "STATE"){
    if (ledState){
      return "ON";
    }
    else{
      return "OFF";
    }
  }
}

setup()

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

Serial.begin(115200);

Set up the ledPin as an OUTPUT and set it to LOW when the program first starts.

pinMode(ledPin, OUTPUT);
digitalWrite(ledPin, LOW);

Initialize Wi-Fi and print the ESP32 IP address on the Serial Monitor.

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());

Initialize WebSocket protocol by calling the initWebSocket() function created previously.

initWebSocket();

Handle Requests

Serve the text saved on the index_html variable when you receive a request on the root / URL – you need to pass the processor function as an argument to replace the placeholders with the current GPIO state.

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

Finally, start the server.

server.begin();

loop()

The LED will be physically controlled on the loop().

void loop() {
  ws.cleanupClients();
  digitalWrite(ledPin, ledState);
}

Note that we all call the cleanupClients() method. Here’s why (explanation from the ESPAsyncWebServer library GitHub page):

Browsers sometimes do not correctly close the WebSocket connection, even when the close() function is called in JavaScript. This will eventually exhaust the web server’s resources and will cause the server to crash. Periodically calling the cleanupClients() function from the main loop()limits the number of clients by closing the oldest client when the maximum number of clients has been exceeded. This can be called every cycle, however, if you wish to use less power, then calling as infrequently as once per second is sufficient.

Demonstration

After inserting your network credentials on the ssid and password variables, you can upload the code to your board. Don’t forget to check if you have the right board and COM port selected.

After uploading the code, open the Serial Monitor at a baud rate of 115200 and press the on-board EN/RST button. The ESP IP address should be printed.

Open a browser on your local network and insert the ESP32 IP address. You should get access to the web page to control the output.

ESP32 WebSocket Server Toggle Outputs Project Overview

Click on the button to toggle the LED. You can open several web browser tabs at the same time or access the web server from different devices and the LED state will be update automatically in all clients whenever there’s a change.

Wrapping Up

In this tutorial you’ve learned how to set up a WebSocket server with the ESP32. The WebSocket protocol allows a full duplex communication between the client and the server. After initializing, the server and the client can exchange data at any given time.

This is very useful because the server can send data to the client whenever something happens. For example, you can add a physical button to this setup that when pressed notifies all clients to update the web interface.

In this example, we’ve shown you how to control one GPIO of the ESP32. You can use this method to control more GPIOs. You can also use the WebSocket protocol to send sensor readings or notifications at any given time.

We hope you’ve found this tutorial useful. We intend to create more tutorials and examples using the WebSocket protocol. So, stay tuned.

Learn more about the ESP32 with our resources:



Build Web Server projects with the ESP32 and ESP8266 boards to control outputs and monitor sensors remotely. Learn HTML, CSS, JavaScript and client-server communication protocols DOWNLOAD »

Build Web Server projects with the ESP32 and ESP8266 boards to control outputs and monitor sensors remotely. Learn HTML, CSS, JavaScript and client-server communication protocols DOWNLOAD »


Enjoyed this project? Stay updated by subscribing our newsletter!

54 thoughts on “ESP32 WebSocket Server: Control Outputs (Arduino IDE)”

  1. Hi RNT team!
    Another very interesting project…Thanks for keeping publishing the results of all your continuous electronics developing efforts!
    As a follow-up, how about a complementary project, this time one client connecting to and controlling the outputs pins of several (ESP32s) servers, all connected servers updating their similarly assigned pin status simultaneously, using the HTTP + the WebSockets protocols?
    Looking forward to hear from you, guys, soon!

    Reply
  2. Hi
    Interesting Article. I am attempting to run this on nodemcu (esp12-e) but get errors when trying to compile

    E:\Documents\Arduino\libraries\AsyncTCP-master\src/AsyncTCP.h:26:23: fatal error: sdkconfig.h: No such file or directory

    #include “sdkconfig.h”

    ^

    compilation terminated.

    Using library WiFi at version 1.2.7 in folder: C:\Program Files\WindowsApps\ArduinoLLC.ArduinoIDE_1.8.42.0_x86__mdqgnx93n4wtt\libraries\WiFi

    Using library AsyncTCP-master at version 1.1.1 in folder: E:\Documents\Arduino\libraries\AsyncTCP-master

    exit status 1

    Error compiling for board NodeMCU 1.0 (ESP-12E Module).

    Are there compatible libraries for the esp-12e???

    regards

    Meir

    Reply
  3. Amazing! I have made a lights automation in my house, so I need to know the state of each light via html page.
    How could I just switch the color of the button when the state changes, instead of ON and OFF words? For instante, yellow for ON and grey for OFF?

    Thank you very much.

    Reply
  4. Hi Rui and Sara, I don’t get much time to do your projects due to a medical issue, but I follow along with your postings. I just love the way you put them all together, especially with the explanation of how the code works and with additional reading references within the project. You both are a great asset to helping those interested in developing their knowledge of various systems and what is available. Thanks also to the readers who contribute. Many thanks to all concerned.

    Reply
  5. Hi Rui.
    to avoid digitalWrite (ledPin, led State); in every cycle I have made these changes to your code.
    do you see any problems in doing it in this way.

    bool event;
    unsigned long check = 1000;

    case WS_EVT_DATA:
    event = true;
    handleWebSocketMessage(arg, data, len)
    break;

    void loop() {

    if (millis() > check) {
    check = millis() + 1000;
    ws.cleanupClients();
    }

    if (event == true)
    {
    digitalWrite(ledPin, ledState);
    event = false;
    }

    }

    Reply
    • maybe this is a better way to handle millis and the roll over issue.

      long eventTimeout=(long)millis()+1000;

      void loop() {

      if((long)millis()-eventTimeout>=0)
      {
      ws.cleanupClients();
      Serial.println(“cleanup”);
      eventTimeout=(long)millis()+1000;
      }

      if (event == true)
      {
      digitalWrite(ledPin, ledState);
      event = false;
      //Serial.println(“event”);
      }
      }

      Reply
  6. Arduino : 1.8.13 (Windows 10), Carte : “NodeMCU-32S, 80MHz, 921600”
    C:\Users\Another\Documents\Arduino\ESP32_WebSocket_Server\ESP32_WebSocket_Server.ino: In function ‘String processor(const String&)’:

    ESP32_WebSocket_Server:201:1: error: control reaches end of non-void function [-Werror=return-type]

    }

    Reply
    • Change The String String processor to this.

      String processor(const String& var){
      Serial.println(var);
      if(var == “STATE”){
      if (ledState){
      return “ON”;
      }
      else{
      return “OFF”;
      }
      }
      return “”;
      }

      Reply
  7. Hi Rui and Sara.
    Thanks for another great tutorial. !!
    I’m running your code on an ESP32 devboard.

    When I refresh the website lot of times, the ESP32 board reboots and I get the error message, shown below.
    It only happens when I use my phone on a WiFi connection.
    When running the website on the computer there are no problems.
    Do you know why this is happening? or does anyone have a solution to this issue.

    CORRUPT HEAP: Bad head at 0x3ffcdc30. Expected 0xabba1234 got 0x3ffce05c
    assertion “head != NULL” failed: file “/home/runner/work/esp32-arduino-lib-builder/esp32-arduino-lib-builder/esp-idf/components/heap/multi_heap_poisoning.c”, line 214, function: multi_heap_free
    abort() was called at PC 0x40105487 on core 0

    regards JB.

    Reply
    • Hi JB,
      I got. the Same Problem. With my iphone sometimes the Webserver Even doesen‘t start. On a PC with Firefox, Chrome the ESP32 works fine.
      Dis you found the reason?
      Regards Chris

      Reply
  8. Hi, very nice project, I am trying to create more outputs and individual buttons for each of output, what is the easiest way to do that?

    Reply
  9. Hi Rui and Sara.
    Thanks for another great tutorial…
    i need to add more GPIO pins to control, please tell me where can i make modifications in this code.

    Reply
  10. This is another great project, I’ve done this project but would like to use websockets for sensor data. Are you planning on a project to do that. Like using a DHT22 sensor. Thanks again for all the great projects, very informative.

    Reply
    • Hi.
      Yes, you can use websockets for that.
      At the moment, we don’t have any tutorial with sensor readings and websockets. But, I’ll add that to my list.
      Regards,
      Sara

      Reply
  11. Hello Sara and Rui,

    I am an avid user of your learning pages. When someone asks me on the forums where they can educate themselves, I never hesitate to inform your site.

    I have 2 small questions regarding this tutorial:

    How to add a second button assigned to a second other ESP32 output.

    How to invert the output state of the pin when starting the ESP32 (if there is a power failure, subsequently, when the power returns, the state of the pins will be on). I went to see the tutorial with the relays and the, that’s what I’m looking for but the concern is that the method used for this tutorial does not update the events instantly.

    Many thanks to you for your work.

    Reply
  12. Bonjour Sara et Rui,
    Merci pour votre tutorial tres explicite.
    J’utilise ce mode pour mon projet actuel ESP8266. C’est parfait…
    Pour finir ce dernier, pourriez-vous m’aider?
    Je souhaite integrer un servo sg90 dans le sketch “ESP Web Server”.
    J’ai: 1- un fichier HTML (un jeu de ma création) qui doit se connecter avec “ESP Web Server” à un servo. Quand le jeu est terminé, et que cela est gagné!!..le jeu declenche un basculement du servo et ouvre un verrou. c’est un jeu en extérieur donc “ESP Web Server” est indispensable.
    Merci de votre aide dans la mesure du possible

    Reply
  13. Rui and Sara,
    Wow, what a great job in explaining the topic. Your postings have been extraordinarily helpful. What a great reference. I just started to learn about arduino and now ESP32 and your pages and videos have been of great help!
    THANK YOU!

    Reply
  14. Hi there, I separated the files into HTML/JS/CSS files to clean it all up a bit. Didn’t change any of the functionality and only had to change a couple of lines. You can download the files at: github.com/rayjamesdev/ESP32-WebSocket-Server-Control-Outputs-Separate-Files

    Good Luck Have Fun! 🙂

    Reply
  15. Hi

    Any suggestions for getting an esp32 plus websockets plus GSM module like the sim7600 working?

    Looks like websockets is easily supported for wifi…but cannot figure out for GSM modules.

    Thanks

    Phil

    Reply
  16. Hi, I loaded the code as is to ESP32 Huzzah.
    Only changed the Led pin to 13 and my credentials of course.

    I can open the page on 3 devices but clicking the button does nothing.
    At some several seconds later I can see the console to show “STATUS”.

    I have updated the AsyncTCP also the ESPAsyncWebServer libraries but no luck.

    What could be the issue…?

    Reply
  17. By the way, the stae of the GPIO does not change at the web pages either.
    Reloading the pasges works ok, just the gpio handling is not.

    Reply
  18. Thank you for your great tutorials!!

    I have loaded the example to a ESP32 Huzzah. Changed the credentials & Gpio from 2 to 13. I can open the page on 3 devices but clicking the button does nothing on either device (laptop, phone).

    I mean, the state of the GPIO does not change on the hardware and at the web pages either.

    Reloading the pages refresh quickly; it is just the Gpio handling is not.

    Several seconds later the console show “STATUS”. it looks like the ESP32 is lagging or not responsive.

    What could be the cause…?

    Reply
  19. Now I have tested with Explorer browser too. It is the same thing.

    I see some code in the code: like:

    console.log(‘Trying to open a WebSocket connection…’);

    But at the Arduino terminal this never shows.
    Where is supposed I will see these messages…?

    console.log(‘Trying to open a WebSocket connection…’);
    console.log(‘Connection opened’);
    console.log(‘Connection closed’);

    Regards.

    Reply
    • Hi Bob, I have exactly the same question! Although I have worked through this tutorial and eveything works, I don’t yet understand what a console is and where one finds it. I would like to do that to be able to fully understand Rui and Sara’s detailed explanations about how the code works.

      If you, or anyone else, knows of any beginners’ guides to seeing these console messages (on PlatformIO on Visual Studio Code on Mac) that would be great. So far I’ve found nothing that I can understand on Google.

      Reply
  20. Well, after a full day and with the help of my teammates we find out the reason.

    It happen the JavaScript code was not executing. The variable “gateway” crashed the browser side. By some unknown reason it not passed the content after your “`” delimiters. At the end it complained by a JavaScript error (Uncaught SyntaxError: Unexpected end of input).

    The fix was to replace your delimiters ( ` ) by apostrophe delimiters ( ‘ ) and to concatenate the “window.location.hostname” :

    var gateway = ‘ws://’ + window.location.hostname + ‘/ws’;

    After that, it worked great.

    Reply
  21. Hello, Rui and Sara. I see a lot of questions here – How do I add multiple buttons? What parts of the code should I edit? Could you make changes to this project so that it has two buttons? I think a lot of people will thank you for that. With great respect for your work.

    Reply
  22. Hello
    excellent tutorial.
    I have even expanded it to 5 buttons as shared by Alex. Thank you.
    I use 3 phones and 2 PCs and they connect perfectly and update as long as it’s on the same local network. However, in one of the phones I have put the public IP of my ESP32 device and in another phone the domain name of my place of installation.
    In both phones I see the web page generated by the server but when I press the button “to activate a certain output, it is not reflected on any side of the connected clients.
    Is it a problem with my modem? I already removed the antivirus and canceled the shields.
    I defined the NAT with port 8080 and the fixed address that I assigned to the WiFi module.
    But there is no client / server communication.
    Can you give me an advice or solution to the external control?
    Thanks

    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.