Building ESP32 Web Server and Control LED in Arduino IDE

The HTTP web server for the ESP32 is a feature that allows the ESP32 microcontroller to serve web pages and handle HTTP requests, making it act as a web server. This capability opens up a world of possibilities for building IoT projects, home automation systems, and other applications where remote control, monitoring, and interaction through a web interface are necessary.

The ESP32’s HTTP web server can handle HTTP GET and POST requests, allowing you to read and send data to and from the ESP32. You can customize the web pages it serves and the actions it performs in response to user interactions, making it highly adaptable for a wide range of projects.

Web server HTTP exchange principle

Table of Contents

ESP32 Web Server Project Overview

In this project, we will explore how to transform an ESP32 microcontroller into a web server capable of controlling two LEDs through a web interface. By combining the ESP32’s Wi-Fi capabilities and its web server functionality, we will create a web-based system that allows users to remotely switch LED on and off from any device with a web browser, such as a computer, smartphone, or tablet. This project serves as an excellent introduction to IoT applications and demonstrates the power of the ESP32 in enabling web-based control and monitoring of connected devices. Whether you are a beginner or an experienced maker, this project offers valuable insights into building web-enabled applications with the ESP32.

Before we get started, make sure you have the following:

  • An ESP32 development board.
  • Arduino IDE is installed on your computer.
  • A stable internet connection.
  • Two LEDs and appropriate resistors.
  • Jumper wires.

Setting Up Arduino IDE for ESP32

  1. Open Arduino IDE and go to “File” -> “Preferences.”
  2. In the “Additional Boards Manager URLs” field, enter the following URL: https://dl.espressif.com/dl/package_esp32_index.json
  3. Go to “Tools” -> “Boards” -> “Boards Manager,” search for “ESP32,” and install the ESP32 board manager.
  4. Select your ESP32 board under “Tools” -> “Board.”

Writing the ESP32 Web Server Code

ESP32 Web Server project wiring diagram

A schematic diagram of the project is shown above. The two LED bulb is controlled by pin 16 and 17  of the ESP32 controller. These LEDs are controlled by a webpage which is connected to the hardware using HTTP protocol.

Include Libraries:

				
					#include <WiFi.h>
				
			

This line includes the necessary library for working with Wi-Fi on the ESP32.

Set Network Configuration:

				
					const char* networkName = "ESP32-Network";
const char* networkPassword = "Esp32-Password";
				
			

Here, you define the network name and password for the ESP32’s Wi-Fi access point. This is the network that clients (devices connecting to your ESP32) will connect to.

Define Server and Variables:

				
					WiFiServer webServer(80);
String httpRequest;
String ledStatePin16 = "off";
String ledStatePin17 = "off";
const int ledPin16 = 16;
const int ledPin17 = 17;
unsigned long currentTime = millis();
unsigned long previousTime = 0;
const long timeout = 2000;
				
			
  • webServer is an object that represents the ESP32’s web server running on port 80.
  • httpRequest will store incoming HTTP requests from clients.
  • ledStatePin16 and ledStatePin17 will store the state of the LEDs (either “on” or “off”).
  • ledPin16 and ledPin17 specify the GPIO pins to which the LEDs are connected.
  • currentTime and previousTime are used for timing client connections, and timeout specifies the maximum time a client can be connected.

Setup Function:

				
					void setup() {
  // Initialize Serial communication
  Serial.begin(115200);
  
  // Set LED pins as OUTPUT and turn them off
  pinMode(ledPin16, OUTPUT);
  digitalWrite(ledPin16, LOW);
  pinMode(ledPin17, OUTPUT);
  digitalWrite(ledPin17, LOW);
  // Configure the ESP32 as a Wi-Fi access point
  WiFi.softAP(networkName, networkPassword);
  
  // Print the ESP32's IP address in the Serial Monitor
  Serial.println("");
  Serial.println("IP address: ");
  Serial.println(WiFi.softAPIP());
  // Start the web server
  webServer.begin();
}
				
			
  • Serial communication is initialized for debugging and logging.
  • The LED pins are configured as OUTPUT and initially turned off.
  • The ESP32 is configured as a Wi-Fi access point using the specified network name and password.
  • The IP address of the ESP32 is printed to the Serial Monitor.
  • The web server is started on port 80.

Loop Function:

				
					void loop() {
  WiFiClient client = webServer.available();
  if (client) {
    currentTime = millis();
    previousTime = currentTime;
    Serial.println("New Client.");
    String currentLine = "";
    while (client.connected() && currentTime - previousTime <= timeout) {
      currentTime = millis();
      if (client.available()) {
        char c = client.read();
        Serial.write(c);
        httpRequest += c;
        if (c == '\n') {
          // Process the incoming HTTP request
          if (currentLine.length() == 0) {
            // Respond to specific HTTP GET requests
            // Toggle LED states and generate HTML response
          } else {
            currentLine = "";
          }
        } else if (c != '\r') {
          currentLine += c;
        }
      }
    }
    // Reset httpRequest, stop the client connection, and print a message to the Serial Monitor
  }
}
				
			
  • In the loop, it checks for incoming client connections to the web server.
  • For each client connection, it processes the incoming HTTP request.
  • If a complete HTTP request is received (indicated by an empty line), it responds to specific GET requests to toggle LED states and generates an HTML response.
  • The client connection is closed after processing the request.
  • The loop continues to listen for new client connections.

Combined Code

				
					#include <WiFi.h>
const char* networkName = "ESP32-Network";
const char* networkPassword = "Esp32-Password";
WiFiServer webServer(80);
String httpRequest;
String ledStatePin16 = "off";
String ledStatePin17 = "off";
const int ledPin16 = 16;
const int ledPin17 = 17;
unsigned long currentTime = millis();
unsigned long previousTime = 0;
const long timeout = 2000;
void setup() {
  Serial.begin(115200);
  
  pinMode(ledPin16, OUTPUT);
  digitalWrite(ledPin16, LOW);
  pinMode(ledPin17, OUTPUT);
  digitalWrite(ledPin17, LOW);
  WiFi.softAP(networkName, networkPassword);
  
  Serial.println("");
  Serial.println("IP address: ");
  Serial.println(WiFi.softAPIP());
  webServer.begin();
}
void loop() {
  WiFiClient client = webServer.available();
  if (client) {
    currentTime = millis();
    previousTime = currentTime;
    Serial.println("New Client.");
    String currentLine = "";
    while (client.connected() && currentTime - previousTime <= timeout) {
      currentTime = millis();
      if (client.available()) {
        char c = client.read();
        Serial.write(c);
        httpRequest += c;
        if (c == '\n') {
          if (currentLine.length() == 0) {
            client.println("HTTP/1.1 200 OK");
            client.println("Content-type:text/html");
            client.println("Connection: close");
            client.println();
            if (httpRequest.indexOf("GET /16/on") >= 0) {
              ledStatePin16 = "on";
              digitalWrite(ledPin16, HIGH);
            } else if (httpRequest.indexOf("GET /16/off") >= 0) {
              ledStatePin16 = "off";
              digitalWrite(ledPin16, LOW);
            }
            
            if (httpRequest.indexOf("GET /17/on") >= 0) {
              ledStatePin17 = "on";
              digitalWrite(ledPin17, HIGH);
            } else if (httpRequest.indexOf("GET /17/off") >= 0) {
              ledStatePin17 = "off";
              digitalWrite(ledPin17, LOW);
            }
            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:,\">");
            client.println("<style>html { font-family: monospace; display: inline-block; margin: 0px auto; text-align: center;}");
            client.println(".button { background-color: yellowgreen; border: none; color: white; padding: 16px 40px;");
            client.println("text-decoration: none; font-size: 32px; margin: 2px; cursor: pointer;}");
            client.println(".button2 {background-color: gray;}</style></head>");
            client.println("<body><h1>ESP32 Web Server</h1>");
            client.println("<p>Control LED State</p>");
            if (ledStatePin16 == "off") {
              client.println("<p><a href=\"/16/on\"><button class=\"button\">OFF</button></a></p>");
            } else {
              client.println("<p><a href=\"/16/off\"><button class=\"button button2\">ON</button></a></p>");
            }
            if (ledStatePin17 == "off") {
              client.println("<p><a href=\"/17/on\"><button class=\"button\">OFF</button></a></p>");
            } else {
              client.println("<p><a href=\"/17/off\"><button class=\"button button2\">ON</button></a></p>");
            }
            client.println("</body></html>");
            client.println();
            break;
          } else {
            currentLine = "";
          }
        } else if (c != '\r') {
          currentLine += c;
        }
      }
    }
    httpRequest = "";
    client.stop();
    Serial.println("Client disconnected.");
    Serial.println("");
  }
}
				
			
Web page display off
Web page display on
esp32 web server Serial monitor
led open state
led off state

Conclusion

In this project, we successfully established an ESP32-based web server capable of controlling two LEDs through a web interface. This endeavor showcases the seamless integration of the ESP32’s Wi-Fi capabilities and web server functionality. By dynamically responding to HTTP requests, we enabled remote LED control, emphasizing the device’s applicability in IoT and home automation. The project not only demonstrates the power of ESP32 for creating web-enabled solutions but also serves as a foundation for expanding IoT applications, ultimately enhancing user accessibility and convenience in controlling connected devices remotely.

More content you may be interested in

esp32 pinout
ESP32 Pinout Reference Guide

The ESP32 is a versatile microcontroller with extensive functionalities. Its pinout includes GPIO pins for digital, analog, and capacitive touch, PWM pins for precise control,

esp32 pwm project
ESP32 PWM Tutorial

This article delves into PWM on the ESP32, crucial for precise control in applications like LED dimming, motor regulation, and audio generation. It explains the

Scroll to Top