Building an ESP32 LED Web Server : A Step-by-Step Guide for IoT Enthusiasts
In the realm of the Internet of Things (IoT), the ESP32 microcontroller offers a powerful solution for creating web servers that respond to requests and serve web pages. In this guide, we will walk through the process of constructing an ESP32 LED web server from the ground up. This project allows you to control LED lights through a web interface, making it an ideal endeavor for both seasoned makers and those venturing into IoT projects.
Materials Required:
To embark on this project, gather the following components:
ESP32 Development Board — The core component for controlling LED lights through the web server.
LED Lights — Utilize any type of LED based on project requirements; for this guide, two 5mm LEDs are used.
Breadboard — Essential for connecting LED lights to the ESP32 microcontroller.
Jumper Wires — Connect the breadboard to the ESP32 and the LED lights.
USB Cable — Establish a connection between the ESP32 Development Board and your computer for programming.
Computer — Required for programming and uploading the code to the ESP32.
Resistor — To limit the current through the LED lights, preventing damage.
Setting up the Circuit:
Connect the LEDs to GPIO pins 12 and 14 on the ESP32, allowing control through the web interface. Ensure a proper connection, and for those opting for the ESP32 Ethernet web server, an Ethernet shield for the ESP32 is needed, along with minor code adjustments.
ESP32 Web Server Operation:
This project functions by transforming the ESP32 into a web server, serving a web page to client devices such as computers or mobile phones over Wi-Fi. The web page provides controls for toggling the LED lights on or off.
Here is a step-by-step breakdown:
The ESP32, functioning as a microcontroller, is connected to LED lights and programmed to serve as a web server.
Web server code is uploaded to the ESP32 using the Arduino IDE or other programming tools.
The ESP32 connects to a Wi-Fi network, enabling communication with client devices.
When a client device connects to the ESP32’s IP address, the web server serves a web page to the client device’s web browser.
The web page incorporates controls for the LED lights, enabling users to turn them on or off.
User interactions with the controls trigger commands to the ESP32, adjusting the LED lights accordingly.
The ESP32 responds to the client device, updating the web page with the current LED lights’ state.
Circuit Diagram:
Refer to the circuit diagram below for connecting the ESP32 with LED lights:
Uploading Code to ESP32:
To upload code to the ESP32 board, follow these steps:
- Connect your ESP32 board to your computer using a USB cable.
- Open the Arduino IDE, select the ESP32 board under “Tools” > “Board,” and choose the correct port.
- Write or copy the provided code into the Arduino IDE.
// Load Wi-Fi library
#include <WiFi.h>
// Replace with your network credentials
const char* ssid = " REPLACE_WITH_YOUR_SSID";
const char* password = " REPLACE_WITH_YOUR_PASSWORD";
// Set web server port number to 80
WiFiServer server(80);
// Variable to store the HTTP request
String header;
// Auxiliary variables to store the current output state
String output12State = "off";
String output14State = "off";
// Assign output variables to GPIO pins
const int output12 = 12;
const int output14 = 14;
// Current time
unsigned long currentTime = millis();
// Previous time
unsigned long previousTime = 0;
// Define timeout time in milliseconds (example: 2000ms = 2s)
const long timeoutTime = 2000;
void setup() {
Serial.begin(115200);
// Initialize the output variables as outputs
pinMode(output12, OUTPUT);
pinMode(output14, OUTPUT);
// Set outputs to LOW
digitalWrite(output12, LOW);
digitalWrite(output14, LOW);
// Connect to Wi-Fi network with SSID and password
Serial.print("Connecting to ");
Serial.println(ssid);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
// Print local IP address and start web server
Serial.println("");
Serial.println("WiFi connected.");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
server.begin();
}
void loop(){
WiFiClient client = server.available(); // Listen for incoming clients
if (client) { // If a new client connects,
currentTime = millis();
previousTime = currentTime;
Serial.println("New Client."); // print a message out in the serial port
String currentLine = ""; // make a String to hold incoming data from the client
while (client.connected() && currentTime - previousTime <= timeoutTime) { // loop while the client's connected
currentTime = millis();
if (client.available()) { // if there's bytes to read from the client,
char c = client.read(); // read a byte, then
Serial.write(c); // print it out the serial monitor
header += c;
if (c == '\n') { // if the byte is a newline character
// if the current line is blank, you got two newline characters in a row.
// that's the end of the client HTTP request, so send a response:
if (currentLine.length() == 0) {
// HTTP headers always start with a response code (e.g. HTTP/1.1 200 OK)
// and a content-type so the client knows what's coming, then a blank line:
client.println("HTTP/1.1 200 OK");
client.println("Content-type:text/html");
client.println("Connection: close");
client.println();
// turns the GPIOs on and off
if (header.indexOf("GET /12/on") >= 0) {
Serial.println("GPIO 12 on");
output12State = "on";
digitalWrite(output12, HIGH);
} else if (header.indexOf("GET /12/off") >= 0) {
Serial.println("GPIO 12 off");
output12State = "off";
digitalWrite(output12, LOW);
} else if (header.indexOf("GET /14/on") >= 0) {
Serial.println("GPIO 14 on");
output14State = "on";
digitalWrite(output14, HIGH);
} else if (header.indexOf("GET /14/off") >= 0) {
Serial.println("GPIO 14 off");
output14State = "off";
digitalWrite(output14, LOW);
}
// Display the HTML web page
client.println("<!DOCTYPE html><html>");
client.println("<head><meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">");
client.println("<link rel=\"icon\" href=\"data:,\">");
// CSS to style the on/off buttons
// Feel free to change the background-color and font-size attributes to fit your preferences
client.println("<style>html { font-family: Helvetica; display: inline-block; margin: 0px auto; text-align: center;}");
client.println(".button { background-color: #4CAF50; border: none; color: white; padding: 16px 40px;");
client.println("text-decoration: none; font-size: 30px; margin: 2px; cursor: pointer;}");
client.println(".button2 {background-color: #555555;}</style></head>");
// Web Page Heading
client.println("<body><h1>ESP32 Web Server</h1>");
// Display current state, and ON/OFF buttons for GPIO 12
client.println("<p>GPIO 12 - State " + output12State + "</p>");
// If the output12State is off, it displays the ON button
if (output12State=="off") {
client.println("<p><a href=\"/12/on\"><button class=\"button\">ON</button></a></p>");
} else {
client.println("<p><a href=\"/12/off\"><button class=\"button button2\">OFF</button></a></p>");
}
// Display current state, and ON/OFF buttons for GPIO 14
client.println("<p>GPIO 14 - State " + output14State + "</p>");
// If the output14State is off, it displays the ON button
if (output14State=="off") {
client.println("<p><a href=\"/14/on\"><button class=\"button\">ON</button></a></p>");
} else {
client.println("<p><a href=\"/14/off\"><button class=\"button button2\">OFF</button></a></p>");
}
client.println("</body></html>");
// The HTTP response ends with another blank line
client.println();
// Break out of the while loop
break;
} else { // if you got a newline, then clear currentLine
currentLine = "";
}
} else if (c != '\r') { // if you got anything else but a carriage return character,
currentLine += c; // add it to the end of the currentLine
}
}
}
// Clear the header variable
header = "";
// Close the connection
client.stop();
Serial.println("Client disconnected.");
Serial.println("");
}
}
- Verify that the code compiles by clicking the “Verify” button.
- Upload the code to the ESP32 board by clicking the “Upload” button.
Finding the IP Address:
- Open the Serial Monitor in the Arduino IDE.
- Set the baud rate to 115200.
- Reset the ESP32 board.
- Wait for the ESP32 to connect to the Wi-Fi network and note the displayed IP address.
Testing the Web Server:
Open a web browser on your computer or mobile device.
Enter the ESP32 board’s IP address in the address bar.
Access the control page and test LED control by clicking “ON” and “OFF” buttons.
This guide meticulously outlines the steps to set up the circuit, upload code, find the IP address, and test the web server. Whether you’re an adept maker or a novice, this project serves as a gateway to enhancing your skills in IoT development. Share us, what new dimensions will you uncover in the realm of ESP32 web servers?
Take a look at the complete tutorial https://www.youtube.com/watch?v=zfXQkv9GbYI&feature=youtu.be
Originally published at https://circuitdigest.com on March 15, 2023