Controlling the brightness of an LED is an easy task. We could do it using code or using wired input. In this tutorial, we will learn how to control the brightness of the LED using a Web Server. The Web Server will have a slider on the browser page which can be controlled by the user.
Few things you might need to know before we get going:
- Installation of the Arduino IDE for the ESP32
- Configuration of the ESP32
- How to create a Web Server using ESP32
- Basic HTML knowledge is recommended
In this tutorial you will learn how to add a slider to the Web Browser Page. Get the value that is stored in a variable and then ESP32 will process it. We will be using the variable to control the PWM pin and increase or decrease the duty cycle depending on the slider value.
Components Required
- ESP32 x 1
- LED x 1
- 220Ω Resistor x 1
- Breadboard
- Jumper Cables
Circuit Diagram
The GPIO2 will be programmed to control the brightness of the LED using the slider on the Web Page. There are various steps that are needed to be done before we get the final result. Basic knowledge of HTML CSS and JavaScript is needed to understand the code of the slider.
We can thereafter control more than one LED with ‘n’ number of sliders. Please note that we have only 16 channels for PWM on the ESP32.
Working Principle
- The ESP32 will be programmed to create a Web Server that will display the Web page with the sliders.
- As we move the sliders, new HTTP requests are sent to the ESP32 with the updated values of the the slider values.
- The HTTP request is in the following format GET/slider?value=SLIDERVALUE. “SLIDERVALUE” will have all the values in the range 0 – 255. We can modify it as per our need, as we can also increase our resolution of the PWM pins.
- After fetching the slider value from the browser, the ESP32 will adjust the duty cycle of the PWM signal and we will be able to see the output.
- This Slider can not be limited only to a LED. The same web slider concept can be used to control many other devices such as servo motor, dc motors, etc.
Code Simplified
// Import required libraries
#include <WiFi.h>
#include <AsyncTCP.h>
#include <ESPAsyncWebServer.h>
// Replace with your network credentials
const char* ssid = "Wifi_name";
const char* password = "Wifi_password";
const int output = 2;
String sliderValue = "0";
// setting PWM properties
const int freq = 5000;
const int ledChannel = 0;
const int resolution = 8;
const char* PARAM_INPUT = "value";
// Create AsyncWebServer object on port 80
AsyncWebServer server(80);
const char index_html[] PROGMEM = R"rawliteral(
<!DOCTYPE HTML><html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>ESP Web Server</title>
<style>
html {font-family: Arial; display: inline-block; text-align: center;}
h2 {font-size: 2.3rem;}
p {font-size: 1.9rem;}
body {max-width: 400px; margin:0px auto; padding-bottom: 25px;}
.slider { -webkit-appearance: none; margin: 14px; width: 360px; height: 25px; background: #FFD65C;
outline: none; -webkit-transition: .2s; transition: opacity .2s;}
.slider::-webkit-slider-thumb {-webkit-appearance: none; appearance: none; width: 35px; height: 35px; background: #003249; cursor: pointer;}
.slider::-moz-range-thumb { width: 35px; height: 35px; background: #003249; cursor: pointer; }
</style>
</head>
<body>
<h2>ESP Web Server</h2>
<p><span id="textSliderValue">%SLIDERVALUE%</span></p>
<p><input type="range" onchange="updateSliderPWM(this)" id="pwmSlider" min="0" max="255" value="%SLIDERVALUE%" step="1" class="slider"></p>
<script>
function updateSliderPWM(element) {
var sliderValue = document.getElementById("pwmSlider").value;
document.getElementById("textSliderValue").innerHTML = sliderValue;
console.log(sliderValue);
var xhr = new XMLHttpRequest();
xhr.open("GET", "/slider?value="+sliderValue, true);
xhr.send();
}
</script>
</body>
</html>
)rawliteral";
// Replaces placeholder with button section in your web page
String processor(const String& var){
//Serial.println(var);
if (var == "SLIDERVALUE"){
return sliderValue;
}
return String();
}
void setup(){
// Serial port for debugging purposes
Serial.begin(115200);
// configure LED PWM functionalitites
ledcSetup(ledChannel, freq, resolution);
// attach the channel to the GPIO to be controlled
ledcAttachPin(output, ledChannel);
ledcWrite(ledChannel, sliderValue.toInt());
// Connect to Wi-Fi
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.println("Connecting to WiFi..");
}
// Print ESP Local IP Address
Serial.println(WiFi.localIP());
// Route for root / web page
server.on("/", HTTP_GET, [](AsyncWebServerRequest *request){
request->send_P(200, "text/html", index_html, processor);
});
// Send a GET request to <ESP_IP>/slider?value=<inputMessage>
server.on("/slider", HTTP_GET, [] (AsyncWebServerRequest *request) {
String inputMessage;
// GET input1 value on <ESP_IP>/slider?value=<inputMessage>
if (request->hasParam(PARAM_INPUT)) {
inputMessage = request->getParam(PARAM_INPUT)->value();
sliderValue = inputMessage;
ledcWrite(ledChannel, sliderValue.toInt());
}
else {
inputMessage = "No message sent";
}
Serial.println(inputMessage);
request->send(200, "text/plain", "OK");
});
// Start server
server.begin();
}
void loop() {
}
Library
We import 3 libraries in this project :
- WiFi – download here
- ESPAsyncWebServer – download here
- ESPAsyncTCP – download here
Download all the above libraries and add them to your library folder.
In your Arduino IDE, you can go to Sketch > Include Library > Add .zip Library and select the libraries you’ve just downloaded.
Before you run the code make sure that the WiFi SSID or name is changed along with the password in the code. Once you do the changes you can upload the code and perform the activity.
Input
The Parameter input PARAM_INPUT variable in the code will have the value of the slider value. This slider value will be received by the ESP32 (GET/slider?value=SLIDERVALUE)
const char* PARAM_INPUT = "value";
Web Page Layout
Customize the layout as per your requirements. The most basic HTML code is used in the above webpage. The slider is created using the input tag in HTML as range. In this input range type, we need to specify the minimum and maximum of the range slider or input.
As we use the ESP32 in 8 bit resolution our range will be from 0-255. We will also add a few different attributes :
- The step attribute specifies the interval between valid numbers. We have set it to 1 in this example
- The id is to update the current slider position on the web page
- The onchange attribute in the input tag is to the call the function updateSliderPWM(this). This function is used to send the HTTP request to the ESP32 when the slider moves. (this) is the value of the slider.
Adding the script to the file
- We will need to add javaScript so that we have a function that keeps on making the request to the ESP32 about the slider value
- The function updateSliderPWM() is the function run continuously on the webpage making the requests to update the slider value.
- The updated slider value is then stored in the variable sliderValue.
- Example when slider value is at 255 we should we get the request as
http://ESP-IP-ADDRESS/slider?value=200
<script>
function updateSliderPWM(element) {
var sliderValue = document.getElementById("pwmSlider").value;
document.getElementById("textSliderValue").innerHTML = sliderValue;
console.log(sliderValue);
var xhr = new XMLHttpRequest();
xhr.open("GET", "/slider?value="+sliderValue, true);
xhr.send();
}
</script>
How to Control the LED?
After uploading the code, the ESP32 will connect to your local network. If you please reset it will try to reconnect again. So in some cases when the ESP32 is already connected make sure you press reset and then enable on the ESP32.
Now you can run the serial monitor on your computer and you will find out the Local IP of your ESP32. Connect to it via a web browser from any device that is connected to the same network.
The ESP32 will get connected to the WiFi and display an IP address. For example : Open the IP address on to your web browser 192.168.100.19
Conclusion
Now you can control the brightness of the LED with the slider on the web browser. Please note that more that 2 browsers can open the IP to control the slider and may have to refresh to fetch the latest slider value.
One Reply on “How to Control LED brightness using a Web Server with the ESP32?”