ESP32 Web Server (WebSocket) with Multiple Sliders: Control LEDs Brightness (PWM)

This tutorial shows how to build an ESP32 web server that displays a web page with multiple sliders. The sliders control the duty cycle of different PWM channels to control the brightness of multiple LEDs. Instead of LEDs, you can use this project to control DC motors or other actuators that require a PWM signal. The communication between the clients and the ESP32 is done using WebSocket protocol. Additionally, whenever there’s a change, all clients update their slider values simultaneously.

ESP32 Web Server WebSocket with Multiple Sliders: Control LEDs Brightness PWM

You can also modify the code presented in this tutorial to add sliders to your projects to set threshold values or any other values you need to use in your code.

For this project, the ESP32 board will be programmed using the Arduino core. You can either use the Arduino IDE, VS Code with PlatformIO, or any other suitable IDE.

To better understand how this project works, we recommend taking a look at the following tutorials:

* This project shows how to build a web server with one slider, but it uses HTTP requests—in this tutorial, we’ll use WebSocket protocol.

We have a similar tutorial for the ESP8266 NodeMCU board:

Project Overview

The following image shows the web page we’ll build for this project:

ESP32 Web Server WebSocket Project overview sliders PWM
  • The web page contains three cards;
  • Each card has a paragraph to display the card title (Fader 1, Fader 2, Fader 3);
  • There’s a range slider in each card that you can move to set the brightness of the corresponding LED;
  • In each card, another paragraph displays the current LED brightness (in percentage);
  • When you set a new position for the slider, it updates all clients (if you have multiple web browser tabs opened (or multiple devices), they update almost simultaneously whenever there’s a change).

How it Works?

  • The ESP hosts a web server that displays a web page with three sliders;
  • When you set a new position for a slider, the client sends the slider number and slider value to the server via WebSocket protocol. For example, if you set slider number 3 to position number 40, it would send this message 3s40 to the server.
ESP32 Web Server Multiple Sliders How it Works
  • The server (ESP) receives the slider number and corresponding value and adjusts the PWM duty cycle accordingly. Additionally, it also notifies all the other clients with the new current slider values—this allows us to have all clients updated almost instantaneously.
ESP32 Sliders Web Server WebSocket Update Clients
  • The ESP32 outputs the PWM signal with the corresponding duty cycle to control the LED brightness. A duty cycle of 0% means the LED is completely off, a duty cycle of 50% means the LED is half lit, and a duty cycle of 100% means the LED is lit;
ESP32 Brightness duty cycle web server PWM example
  • Whenever you open a new web browser window (this is when a new client connects), it will send a message to the ESP32 (also through WebSocket protocol) with the message getValues. When the ESP32 gets this message, it sends the current slider values. This way, whenever you open a new tab, it always shows the current and updated values.
ESP32 Multiple Sliders Web Server New Client Update Values

Prerequisites

Before proceeding with this tutorial, make sure you check all the following prerequisites.

1) Parts Required

To follow this project you need:

You don’t need three LEDs to test this project, you can simply see the results in the Serial Monitor or use other actuators that required a PWM signal to operate.

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!

2) Arduino IDE and ESP32 Boards Add-on

We’ll program the ESP32 using Arduino IDE. So, you must have the ESP32 add-on installed. Follow the next tutorial if you haven’t already:

If you want to use VS Code with the PlatformIO extension, follow the next tutorial instead to learn how to program the ESP32:

3) Filesystem Uploader Plugin

To upload the HTML, CSS, and JavaScript files needed to build this project to the ESP32 flash memory (SPIFFS), we’ll use a plugin for Arduino IDE: SPIFFS Filesystem uploader. Follow the next tutorial to install the filesystem uploader plugin if you haven’t already:

If you’re using VS Code with the PlatformIO extension, read the following tutorial to learn how to upload files to the filesystem:

4) Libraries

To build this project, you need to install the following libraries:

You can install the first library using the Arduino Library Manager. Go to Sketch Include Library > Manage Libraries and search for the library name.

The ESPAsyncWebServer and AsynTCP 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 SketchInclude Library > Add .zip Library and select the libraries you’ve just downloaded.

Installing Libraries (VS Code + PlatformIO)

If you’re programming the ESP32 using PlatformIO, you should add the following lines to the platformio.ini file to include the libraries (also change the Serial Monitor speed to 115200):

monitor_speed = 115200
lib_deps = ESP Async WebServer
	arduino-libraries/Arduino_JSON @ 0.1.0

Schematic Diagram

Wire three LEDs to the ESP32. We’re using GPIOs 12, 13, and 14. You can use any other suitable GPIOs.

ESP32 connected to three LEDs Schematic diagram wiring circuit

Recommended reading: ESP32 Pinout Reference: Which GPIO pins should you use?

Organizing Your Files

To keep the project organized and make it easier to understand, we’ll create four files to build the web server:

  • Arduino sketch that handles the web server;
  • index.html: to define the content of the web page;
  • sytle.css: to style the web page;
  • script.js: to program the behavior of the web page—handle what happens when you move the slider, send, receive and interpret the messages received via WebSocket protocol.
Organizing your Files arduino sketch index html style css script js

You should save the HTML, CSS, and JavaScript files inside a folder called data inside the Arduino sketch folder, as shown in the previous diagram. We’ll upload these files to the ESP32 filesystem (SPIFFS).

You can download all project files:

HTML File

Copy the following to the index.html file.

<!-- Complete project details: https://randomnerdtutorials.com/esp32-web-server-websocket-sliders/ -->

<!DOCTYPE html>
<html>
<head>
    <title>ESP IOT DASHBOARD</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="icon" type="image/png" href="favicon.png">
    <link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
    <div class="topnav">
        <h1>Multiple Sliders</h1>
    </div>
    <div class="content">
        <div class="card-grid">
            <div class="card">
                <p class="card-title">Fader 1</p>
                <p class="switch">
                    <input type="range" onchange="updateSliderPWM(this)" id="slider1" min="0" max="100" step="1" value ="0" class="slider">
                </p>
                <p class="state">Brightness: <span id="sliderValue1"></span> &percnt;</p>
            </div>
            <div class="card">
                <p class="card-title"> Fader 2</p>
                <p class="switch">
                    <input type="range" onchange="updateSliderPWM(this)" id="slider2" min="0" max="100" step="1" value ="0" class="slider">
                </p>
                <p class="state">Brightness: <span id="sliderValue2"></span> &percnt;</p>
            </div>
            <div class="card">
                <p class="card-title"> Fader 3</p>
                <p class="switch">
                    <input type="range" onchange="updateSliderPWM(this)" id="slider3" min="0" max="100" step="1" value ="0" class="slider">
                </p>
                <p class="state">Brightness: <span id="sliderValue3"></span> &percnt;</p>
            </div>
        </div>
    </div>
    <script src="script.js"></script>
</body>
</html>

View raw code

Let’s take a quick look at the most relevant parts of the HTML file.

Creating a Slider

The following tags create the card for the first slider (Fader 1).

<div class="card">
  <p class="card-title">Fader 1</p>
  <p class="switch">
    <input type="range" onchange="updateSliderPWM(this)" id="slider1" min="0" max="100" step="1" value ="0" class="slider">
  </p>
  <p class="state">Brightness: <span id="sliderValue1"></span> &percnt;</p>
</div>

The first paragraph displays a title for the card (Fader 1). You can change the text to whatever you want.

<p class="card-title">Fader 1</p>

To create a slider in HTML you use the <input> tag. The <input> tag specifies a field where the user can enter data.

There are a wide variety of input types. To define a slider, use the type attribute with the range value. In a slider, you also need to define the minimum and the maximum range using the min and max attributes (in this case, 0 and 100, respectively).

You also need to define other attributes like:

  • the step attribute specifies the interval between valid numbers. In our case, we set it to 1;
  • the class to style the slider (class=”slider”);
  • the id so that we can manipulate the slider value using JavaScript (id=”slider1″);
  • the onchange attribute to call a function (updateSliderPWM(this)) when you set a new position for the slider. This function (defined in the JavaScript file) sends the current slider value via the WebSocket protocol to the client. The this keyword refers to the HTML slider element.

The slider is inside a paragraph with the switch class name. So, here are the tags that actually create the slider.

<p class="switch">
  <input type="range" onchange="updateSliderPWM(this)" id="slider1" min="0" max="100" step="1" value ="0" class="slider">
</p>

Finally, there’s a paragraph with a <span> tag, so that we can insert the current slider value in that paragraph by referring to its id (id=”sliderValue1″).

<p class="state">Brightness: <span id="sliderValue1"></span> &percnt;</p>

Creating More Sliders

To create more sliders, you need to copy all the HTML tags that create the complete card. First, however, you need to consider that you need a unique id for each slider and slider value. In our case, we have three sliders with the following ids: slider1, slider2, slider3, and three placeholders for the slider value with the following ids: sliderValue1, sliderValue2, sliderValue3.

For example, here’s the card for slider number 2.

<div class="card">
  <p class="card-title"> Fader 2</p>
  <p class="switch">
    <input type="range" onchange="updateSliderPWM(this)" id="slider2" min="0" max="100" step="1" value ="0" class="slider">
  </p>
  <p class="state">Brightness: <span id="sliderValue2"></span> &percnt;</p>
</div>

CSS File

Copy the following to the style.css file.

/*  Complete project details: https://randomnerdtutorials.com/esp32-web-server-websocket-sliders/  */

html {
    font-family: Arial, Helvetica, sans-serif;
    display: inline-block;
    text-align: center;
  }
  h1 {
    font-size: 1.8rem;
    color: white;
  }
  p {
    font-size: 1.4rem;
  }
  .topnav {
    overflow: hidden;
    background-color: #0A1128;
  }
  body {
    margin: 0;
  }
  .content {
    padding: 30px;
  }
  .card-grid {
    max-width: 700px;
    margin: 0 auto;
    display: grid;
    grid-gap: 2rem;
    grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  }
  .card {
    background-color: white;
    box-shadow: 2px 2px 12px 1px rgba(140,140,140,.5);
  }
  .card-title {
    font-size: 1.2rem;
    font-weight: bold;
    color: #034078
  }
  .state {
    font-size: 1.2rem;
    color:#1282A2;
  }
  .slider {
    -webkit-appearance: none;
    margin: 0 auto;
    width: 100%;
    height: 15px;
    border-radius: 10px;
    background: #FFD65C;
    outline: none;
  }
  .slider::-webkit-slider-thumb {
    -webkit-appearance: none;
    appearance: none;
    width: 30px;
    height: 30px;
    border-radius: 50%;
    background: #034078;
    cursor: pointer;
  }
  .slider::-moz-range-thumb {
    width: 30px;
    height: 30px;
    border-radius: 50% ;
    background: #034078;
    cursor: pointer;
  }
  .switch {
    padding-left: 5%;
    padding-right: 5%;
  }

View raw code

Let’s take a quick look at the relevant parts of the CSS file that style the slider. In this example, we need to use the vendor prefixes for the appearance attribute.

.slider {
  -webkit-appearance: none;
  margin: 0 auto;
  width: 100%;
  height: 15px;
  border-radius: 10px;
  background: #FFD65C;
  outline: none;
}
.slider::-webkit-slider-thumb {
  -webkit-appearance: none;
  appearance: none;
  width: 30px;
  height: 30px;
  border-radius: 50%;
  background: #034078;
  cursor: pointer;
}
.slider::-moz-range-thumb {
  width: 30px;
  height: 30px;
  border-radius: 50% ;
  background: #034078;
  cursor: pointer;
}
.switch {
  padding-left: 5%;
  padding-right: 5%;
}

Vendor Prefixes

Vendor prefixes allow a browser to support new CSS features before they become fully supported. The most commonly used browsers use the following prefixes:

  • -webkit- Chrome, Safari, newer versions of Opera, almost all iOS browsers,
  • -moz- Firefox,
  • -o- Old versions of Opera,
  • -ms- Microsoft Edge and Internet Explorer.

Vendor prefixes are temporary. Once the properties are fully supported by the browser you use, you don’t need them. You can use the following reference to check if the property you’re using needs prefixes: http://shouldiprefix.com/

Let’s take a look at the .slider selector (styles the slider itself):

.slider {
  -webkit-appearance: none;
  margin: 0 auto;
  width: 100%;
  height: 15px;
  border-radius: 10px;
  background: #FFD65C;outline: none;
}

Setting -webkit-appearance to none overrides the default CSS styles applied to the slider in Google Chrome, Safari, and Android browsers.

-webkit-appearance: none;

Setting the margin to 0 auto aligns the slider inside its parent container.

margin: 0 auto;

The width of the slider is set to 100% and the height to 15px. The border-radius is set to 10px.

margin: 0 auto;
width: 100%;
height: 15px;
border-radius: 10px;

Set the background color for the slider and set the outline to none.

background: #FFD65C;
outline: none;

Then, format the slider handle. Use -webkit- for Chrome, Opera, Safari and Edge web browsers and -moz- for Firefox.

.slider::-webkit-slider-thumb {
  -webkit-appearance: none;
  appearance: none;
  width: 30px;
  height: 30px;
  border-radius: 50%;
  background: #034078;
  cursor: pointer;
}
.slider::-moz-range-thumb {
  width: 30px;
  height: 30px;
  border-radius: 50% ;
  background: #034078;
  cursor: pointer;
}

Set the -webkit-appearance and appearance properties to none to override default properties.

-webkit-appearance: none;
appearance: none;

Set a specific width, height and border-radius for the handler. Setting the same width and height with a border-radius of 50% creates a circle.

width: 30px;
height: 30px;
border-radius: 50%;

Then, set a color for the background and set the cursor to a pointer.

background: #034078;
cursor: pointer;

Feel free to play with the slider properties to give it a different look.

JavaScript File

Copy the following to the script.js file.

// Complete project details: https://randomnerdtutorials.com/esp32-web-server-websocket-sliders/

var gateway = `ws://${window.location.hostname}/ws`;
var websocket;
window.addEventListener('load', onload);

function onload(event) {
    initWebSocket();
}

function getValues(){
    websocket.send("getValues");
}

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

function onOpen(event) {
    console.log('Connection opened');
    getValues();
}

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

function updateSliderPWM(element) {
    var sliderNumber = element.id.charAt(element.id.length-1);
    var sliderValue = document.getElementById(element.id).value;
    document.getElementById("sliderValue"+sliderNumber).innerHTML = sliderValue;
    console.log(sliderValue);
    websocket.send(sliderNumber+"s"+sliderValue.toString());
}

function onMessage(event) {
    console.log(event.data);
    var myObj = JSON.parse(event.data);
    var keys = Object.keys(myObj);

    for (var i = 0; i < keys.length; i++){
        var key = keys[i];
        document.getElementById(key).innerHTML = myObj[key];
        document.getElementById("slider"+ (i+1).toString()).value = myObj[key];
    }
}

View raw code

Here’s a list of what this code does:

  • initializes a WebSocket connection with the server;
  • sends a message to the server to get the current slider values;
  • uses the response to update the slider values on the web page;
  • handles data exchange through the WebSocket protocol.

Let’s take a look at this JavaScript code to see how it works.

The gateway is the entry point to the WebSocket interface. window.location.hostname gets the current page address (the web server IP address).

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

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.

function onload(event) {
  initWebSocket();
}

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;
}

Note that when the websocket connection in open, we’ll call the getValues function.

function onOpen(event) {
  console.log('Connection opened');
  getValues();
}

The getValues() function sends a message to the server getValues to get the current value of all sliders. Then, we must handle what happens when we receive that message on the server side (ESP32).

function getStates(){
  websocket.send("getValues");
}

We handle the messages received via websocket protocol on the onMessage() function.

function onMessage(event) {
  console.log(event.data);
  var myObj = JSON.parse(event.data);
  var keys = Object.keys(myObj);

  for (var i = 0; i < keys.length; i++){
    var key = keys[i];
    document.getElementById(key).innerHTML = myObj[key];
    document.getElementById("slider"+ (i+1).toString()).value = myObj[key];
  }
}

The server sends the states in JSON format, for example:

{
  sliderValue1 : 20;
  sliderValue2: 50;
  sliderValue3: 0;
}

The onMessage() function simply goes through all the values and places them on the corresponding places on the HTML page.

The updateSliderPWM() function runs when you move the sliders.

function updateSliderPWM(element) {
  var sliderNumber = element.id.charAt(element.id.length-1);
  var sliderValue = document.getElementById(element.id).value;
  document.getElementById("sliderValue"+sliderNumber).innerHTML = sliderValue;
  console.log(sliderValue);
  websocket.send(sliderNumber+"s"+sliderValue.toString());
}

This function gets the value from the slider and updates the corresponding paragraph with the right value. This function also sends a message to the server so that the ESP32 updates the LED brightness.

websocket.send(sliderNumber+"s"+sliderValue.toString());

The message is sent in the following format:

  • slidernumbersslidervalue

For example, if you move slider number 3 to position 40, it will send the following message:

3s40

Arduino Sketch

Copy the following code to your Arduino IDE or to the main.cpp file if you’re using PlatformIO.

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

#include <Arduino.h>
#include <WiFi.h>
#include <AsyncTCP.h>
#include <ESPAsyncWebServer.h>
#include "SPIFFS.h"
#include <Arduino_JSON.h>

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

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

AsyncWebSocket ws("/ws");
// Set LED GPIO
const int ledPin1 = 12;
const int ledPin2 = 13;
const int ledPin3 = 14;

String message = "";
String sliderValue1 = "0";
String sliderValue2 = "0";
String sliderValue3 = "0";

int dutyCycle1;
int dutyCycle2;
int dutyCycle3;

// setting PWM properties
const int freq = 5000;
const int ledChannel1 = 0;
const int ledChannel2 = 1;
const int ledChannel3 = 2;

const int resolution = 8;

//Json Variable to Hold Slider Values
JSONVar sliderValues;

//Get Slider Values
String getSliderValues(){
  sliderValues["sliderValue1"] = String(sliderValue1);
  sliderValues["sliderValue2"] = String(sliderValue2);
  sliderValues["sliderValue3"] = String(sliderValue3);

  String jsonString = JSON.stringify(sliderValues);
  return jsonString;
}

// Initialize SPIFFS
void initFS() {
  if (!SPIFFS.begin()) {
    Serial.println("An error has occurred while mounting SPIFFS");
  }
  else{
   Serial.println("SPIFFS mounted successfully");
  }
}

// Initialize WiFi
void initWiFi() {
  WiFi.mode(WIFI_STA);
  WiFi.begin(ssid, password);
  Serial.print("Connecting to WiFi ..");
  while (WiFi.status() != WL_CONNECTED) {
    Serial.print('.');
    delay(1000);
  }
  Serial.println(WiFi.localIP());
}

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

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;
    message = (char*)data;
    if (message.indexOf("1s") >= 0) {
      sliderValue1 = message.substring(2);
      dutyCycle1 = map(sliderValue1.toInt(), 0, 100, 0, 255);
      Serial.println(dutyCycle1);
      Serial.print(getSliderValues());
      notifyClients(getSliderValues());
    }
    if (message.indexOf("2s") >= 0) {
      sliderValue2 = message.substring(2);
      dutyCycle2 = map(sliderValue2.toInt(), 0, 100, 0, 255);
      Serial.println(dutyCycle2);
      Serial.print(getSliderValues());
      notifyClients(getSliderValues());
    }    
    if (message.indexOf("3s") >= 0) {
      sliderValue3 = message.substring(2);
      dutyCycle3 = map(sliderValue3.toInt(), 0, 100, 0, 255);
      Serial.println(dutyCycle3);
      Serial.print(getSliderValues());
      notifyClients(getSliderValues());
    }
    if (strcmp((char*)data, "getValues") == 0) {
      notifyClients(getSliderValues());
    }
  }
}
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);
}


void setup() {
  Serial.begin(115200);
  pinMode(ledPin1, OUTPUT);
  pinMode(ledPin2, OUTPUT);
  pinMode(ledPin3, OUTPUT);
  initFS();
  initWiFi();

  // configure LED PWM functionalitites
  ledcSetup(ledChannel1, freq, resolution);
  ledcSetup(ledChannel2, freq, resolution);
  ledcSetup(ledChannel3, freq, resolution);

  // attach the channel to the GPIO to be controlled
  ledcAttachPin(ledPin1, ledChannel1);
  ledcAttachPin(ledPin2, ledChannel2);
  ledcAttachPin(ledPin3, ledChannel3);


  initWebSocket();
  
  // Web Server Root URL
  server.on("/", HTTP_GET, [](AsyncWebServerRequest *request){
    request->send(SPIFFS, "/index.html", "text/html");
  });
  
  server.serveStatic("/", SPIFFS, "/");

  // Start server
  server.begin();

}

void loop() {
  ledcWrite(ledChannel1, dutyCycle1);
  ledcWrite(ledChannel2, dutyCycle2);
  ledcWrite(ledChannel3, dutyCycle3);

  ws.cleanupClients();
}

View raw code

How the Code Works

Let’s take a quick look at the relevant parts for this project. To better understand how the code works, we recommend following this tutorial about WebSocket protocol with the ESP32 and this tutorial about PWM with the ESP32.

Insert your network credentials in the following variables to connect the ESP32 to your local network:

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

The getSliderValues() function creates a JSON string with the current slider values.

String getSliderValues(){
  sliderValues["sliderValue1"] = String(sliderValue1);
  sliderValues["sliderValue2"] = String(sliderValue2);
  sliderValues["sliderValue3"] = String(sliderValue3);

  String jsonString = JSON.stringify(sliderValues);
  return jsonString;
}

The notifyClients() function notifies all clients with the current slider values. Calling this function is what allows us to notify changes in all clients whenever you set a new position for a slider.

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

The handleWebSocketMessage(), as the name suggests, handles what happens when the server receives a message from the client via WebSocket protocol. We’ve seen in the JavaScript file, that the server can receive the getValues message or a message with the slider number and the slider value.

When it receives the getValues message, it sends the current slider values.

if (strcmp((char*)data, "getValues") == 0) {
  notifyClients(getSliderValues());
}

If it receives another message, we check to which slider corresponds the message and update the corresponding duty cycle value. Finally, we notify all clients that a change occurred. Here’s an example for slider 1:

if (message.indexOf("1s") >= 0) {
  sliderValue1 = message.substring(2);
  dutyCycle1 = map(sliderValue1.toInt(), 0, 100, 0, 255);
  Serial.println(dutyCycle1);
  Serial.print(getSliderValues());
  notifyClients(getSliderValues());
}

In the loop(), we update the duty cycle of the PWM channels to adjust the brightness of the LEDs.

void loop() {
  ledcWrite(ledChannel1, dutyCycle1);
  ledcWrite(ledChannel2, dutyCycle2);
  ledcWrite(ledChannel3, dutyCycle3);

  ws.cleanupClients();
}

Upload Code and Files

After inserting your network credentials, save the code. Go to Sketch > Show Sketch Folder, and create a folder called data.

Arduino IDE Open Sketch Folder to create data folder

Inside that folder you should save the HTML, CSS and JavaScript files.

Then, upload the code to your ESP32 board. Make sure you have the right board and COM port selected. Also, make sure you’ve added your network credentials.

Upload Arduino code

After uploading the code, you need to upload the files. Go to Tools ESP32 Data Sketch Upload and wait for the files to be uploaded.

ESP32 Sketch Data Upload SPIFFS Arduino IDE

When everything is successfully uploaded, open the Serial Monitor at a baud rate of 115200. Press the ESP32 EN/RST button, and it should print the ESP32 IP address.

Demonstration

Open a browser on your local network and paste the ESP32 IP address. You should get access to the web server page to control the brightness of the LEDs.

Move the sliders to control the brightness of the LEDs.

ESP32 Multiple Sliders Web Server Webscocket Arduino

Open several tabs or connect to the web server using another device, and notice that the slider values update almost instantaneously whenever there’s a change.

You can watch the video demonstration:

Wrapping Up

In this tutorial, you’ve learned how to build a web server with the ESP32 that serves a web page with multiple sliders. The sliders allow you to control the brightness of LEDs connected to the ESP32. In addition, we’ve used the WebSocket protocol to communicate between the ESP32 and the clients.

We hope you had learned a lot from this tutorial. Let us know in the comments below if you successfully followed this tutorial and got the project working.

To learn more about building web servers with the ESP32, we really recommend taking a look at our eBook:

Learn more about the ESP32 with our resources:

Thank you for reading.



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 »

Recommended Resources

Build a Home Automation System from Scratch » With Raspberry Pi, ESP8266, Arduino, and Node-RED.

Home Automation using ESP8266 eBook and video course » Build IoT and home automation projects.

Arduino Step-by-Step Projects » Build 25 Arduino projects with our course, even with no prior experience!

What to Read Next…


Enjoyed this project? Stay updated by subscribing our newsletter!

29 thoughts on “ESP32 Web Server (WebSocket) with Multiple Sliders: Control LEDs Brightness (PWM)”

  1. Hi,

    I like your projects and tutorials but I’m not a web programmer and this is keeping me from experimenting :).

    Other than App inventor is there another app you could propose me that would translate the graphics ptogramming to html code ?

    Kind regards,

    Mario

    Reply
  2. Hi I saw your new project, I loaded the sketch and it is compiled correctly , I followed all your instructions but in the browser web page at the IP address of the ESP32 nothing is displayed. What do you suggest me to check.

    Thanks
    Massimo

    Reply
    • Hi.
      You’ve probably didn’t upload the files to the filesystem.
      The files in the data folder.
      Regards,
      Sara

      Reply
        • Ciao, ho scompattato il file zip che ho scaricato dal sito, lo sketch e i file HTML, CSS e JAvaScript sono nella cartella “data”. Inoltre dal monitor seriale sembra che vada tutto bene ed ottengo il messaggio seguente:
          ” SPIFFS mounted successfully ”
          ” Connecting to WiFi …192.168.1.64 ”
          tuttavia la pagina web all’indirizzo 192.168.1.64 risulta vuota.

          Reply
          • Hi Sara, ok now everything works, it was my first sketch with SPIFFS, I didn’t understand how to load the HTML, CSS and JAvaScript files in the ESP32 device, I thought they were loaded at compile time, now I used the function from the tools menu and everything went to its place.
            Congratulations on your project.
            Thanks
            Regards
            Massimo

  3. I tried the schetch on two different ESP32 devices, but apart from the different IP address the result is the same

    Reply
  4. Great tutorial like always. I like the explanation of the code.

    I have your book “Home Automation using ESP8266 eBook and video course” and learned a lot. If you ever revise it, I hope you include the ESP32. I don’t use the ESP8266 boards, just the ESP32 boards

    Reply
  5. Hello. First off, I was getting inconsistent results with the LEDs… Nothing happened until 50% then as I went further the LEDs would brighten, dim then brighten again.

    I changed the mapped duty cycle from 1024 (10 bit) to 255 (8-bit) and everything worked properly. Not sure why you have 1024 (10 bit) setup for an LED? Am I missing somthing here?

    As a side note: I wired an RGB LED instead of using discrete ones, and due to the fact that all I had was Common Anode, I had to modify the loop commands like so, to “reverse the effect” back to normal 🙂

    void loop() {
    ledcWrite(ledChannel1, 255-dutyCycle1); // -255 for Common Anode
    ledcWrite(ledChannel2, 255-dutyCycle2); // -255 for Common Anode
    ledcWrite(ledChannel3, 255-dutyCycle3); // -255 for Common Anode

    Reply
    • Hi.
      Thanks for pointing that out.
      You’re right about the mapping (our mistake).
      We’ll fix the code.
      Regards,
      Sara

      Reply
  6. Great tutorial, txs.

    For I while now, I’ve been looking for a solution to control the brightness of standard 12V LED downlights in my home. Would I be able to use this for that purpose?

    Reply
    • Of course you could…but you would need appropriate MOSFET drivers, and they truly have to be 12V LED modules. Many have built in drivers, and those probably won’t work.

      Most down lights for homes in the US are not 12V. To use this project, there can be nothing in the light circuit but a resistor(s) and the LEDs themselves. You simple insert the MOSFET in line with the LED, and control the gate with the PWM from the ESP. The MOSFET used has to be a logic level gate, and I like the BTS 141 (low side switch) for use with 3.3v microprocessors. If there is any existing sort of driver module you would need to know if that is controllable with PWM….if so, (usually not) then you are good to go!

      Reply
  7. I was wondering how to add a password to the server to only let those with it to run the LED, motors etc.

    Or simpler how would you load it into the ESP32 and then call the program. The password page can pop up first, but then how will it call the slider HTML/CSS/Jscript page???

    Thank you for your thoughts.

    Reply
  8. I would give you both a complement for the information on the site, the books and the time you need for answer the questions. And the transparency of the answers.
    😉

    Reply
    • Hi.
      It works like that.
      But, it should be sliderValues. We updated the code.
      Thanks for noticing.
      Regards,
      sara

      Reply
  9. Hello Rui & Sara,
    I have this up & running, & would like to be able to also modify the slider output internally in the ESP32. I tried adding the following to the loop, and I see the values are updated on the serial monitor, but not on the connected device webpage. Also, the Output to the LED connected to the ESP32 only varies when I move the slider. (Even tho I am changing the value of sliderValue1 in code)
    How would I do this to make the LED variable either by the ESP directly, or by user input from a Web Page?

    [code]
    currentMillis = millis();

    if((currentMillis - lastMillis) > interval)
    {
    tempSliderValue = sliderValue1.toInt();
    if(tempSliderValue < 100)
    {
    tempSliderValue += 1;
    }
    else tempSliderValue = 0;

    sliderValue1 = String(tempSliderValue);
    notifyClients(getSliderValues());
    Serial.print(tempSliderValue);
    Serial.print(" ");
    Serial.println(sliderValue1);
    lastMillis = currentMillis;
    }

    [/code]

    Reply
  10. Very Nice example, However I have many questions. How does one even began to
    understand webservers from scratch. Some people can read through code as if it was straight reading. JavaScript I can follow somewhat lets say 50%; you add this to we socket and other stuff and now we have a challenge on our hands.

    I am thinking starting with libraries would get me the format used possibly in the main files, but the time to get through this would be a life time?

    I am assuming if you want a webserver; one just buys it and configures into the the system similar to ethernet stacks and USB stacks;

    Phil

    Reply
  11. Have been trying this slider project several times with different board and different devices like phones, PC’s and pads. Uploaded the code and got the IP address. When putting the IP address in the browser of any device it comes up” This website is not secure and the “padlock” shows. Where have I got it wrong?

    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.