ESP32 Web Server – Control LED Using Wi-Fi and Smartphone

In this project, we will learn how to create a simple web server using the ESP32 and control an LED wirelessly through a smartphone or computer browser.

The ESP32 connects to a Wi-Fi network and hosts a webpage containing two buttons: LED ON and LED OFF. By pressing these buttons, we can control an LED connected to the ESP32 without using a separate mobile application.

This project is part of the DigitalLab ESP32 Beginner Series – EP4.

Project Overview

The ESP32 has built-in Wi-Fi capabilities that allow it to connect to a wireless network and communicate with other devices.

In this project, we use this feature to create a web server. Once connected to Wi-Fi, the ESP32 receives an IP address from the router.

We can enter this IP address in a smartphone browser to access a webpage hosted directly by the ESP32.

The webpage provides LED ON and OFF buttons. When a button is pressed, the browser sends an HTTP request to the ESP32, which changes the state of the connected LED.

No dedicated mobile application or cloud service is required. The smartphone and ESP32 communicate over the same local Wi-Fi network.

Components Required

  • ESP32 DevKit V1 – 38-pin board
  • 5mm LED
  • 220Ω resistor
  • Breadboard
  • Jumper wires
  • USB cable
  • Wi-Fi router
  • Smartphone or computer

Circuit Connections

We use GPIO 25 to control the LED.

ComponentESP32 Connection
LED Anode (+)GPIO 25 through 220Ω resistor
LED Cathode (−)GND

The resistor limits the current flowing through the LED and protects it from damage.

Project Implementation

The project is completed in three stages.

Stage 1 – Connecting ESP32 to Wi-Fi

In the first stage, we connect the ESP32 to an available Wi-Fi network using the Arduino IDE.

We use the ESP32 Wi-Fi library and the WiFi.begin() function to establish the connection.

Once connected, the ESP32 displays the following information in the Serial Monitor:

  • Wi-Fi connection status
  • IP address assigned by the router
  • Wi-Fi signal strength

The IP address is important because we will use it to access the ESP32 web server in the next stage.

// ********************************************************************************************//
// ** Program to Connect to Wifi network and display status and IP Address on Serial Monitor **//
//*********************************************************************************************//

#include <WiFi.h>

// Enter your Wi-Fi credentials
const char* ssid = "YOUR_SSID";
const char* password = "YOUR_PASSWORD";

void setup() {
  Serial.begin(115200);

  delay(1000);

  Serial.println();
  Serial.println("ESP32 Wi-Fi Connection");
  Serial.println("----------------------");

  // Start Wi-Fi connection
  WiFi.begin(ssid, password);

  Serial.print("Connecting to Wi-Fi");

  // Wait until connected
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }

  Serial.println();
  Serial.println("Wi-Fi Connected!");

  // Display network information
  Serial.print("IP Address: ");
  Serial.println(WiFi.localIP());

  Serial.print("Signal Strength (RSSI): ");
  Serial.print(WiFi.RSSI());
  Serial.println(" dBm");
}

void loop() {
  // Nothing required for Stage 1
}

Stage 2 – Creating an ESP32 Web Server

In the second stage, we create a basic web server using the ESP32.

The ESP32 listens for incoming browser requests on port 80.

We use the Arduino WebServer library to handle HTTP requests and send an HTML webpage to the browser.

The webpage contains:

  • ESP32 Web Server heading
  • Welcome message
  • Wi-Fi connection information
  • Basic HTML and CSS styling

After uploading the program, we enter the ESP32 IP address in a smartphone or computer browser.

The webpage hosted by the ESP32 opens directly in the browser.

Organizing the Code into Separate Files

To make the program easier to understand and maintain, we separate the web server functionality into three files.

1. Main Arduino Sketch (.ino)

Handles the Wi-Fi connection and calls the web server functions.

2. WebServerCode.h

Contains the declarations of the web server functions.

3. WebServerCode.cpp

Contains the web server implementation, HTML webpage and request-handling functions.

This approach keeps the main program simple and makes it easier to extend the project in future episodes.

Below is the coe for WebServerCode.cpp

#include <Arduino.h>
#include <WebServer.h>
#include "WebServerCode.h"

// Create web server on port 80
WebServer server(80);

// Webpage HTML
const char webpage[] PROGMEM = R"rawliteral(
<!DOCTYPE html>
<html>
<head>
  <title>ESP32 Web Server</title>

  <meta name="viewport"
        content="width=device-width, initial-scale=1">

  <style>
    body {
      font-family: Arial, sans-serif;
      text-align: center;
      background-color: #f2f2f2;
      margin-top: 60px;
    }

    h1 {
      color: #0066cc;
    }

    .box {
      background: white;
      padding: 25px;
      margin: 20px auto;
      max-width: 350px;
      border-radius: 12px;
      box-shadow: 0 2px 8px #cccccc;
    }

    p {
      font-size: 18px;
    }
  </style>
</head>

<body>
  <div class="box">
    <h1>ESP32 Web Server</h1>
    <p>Welcome to DigitalLab!</p>
    <p>ESP32 is successfully connected to Wi-Fi.</p>
    <p>Stage 2: Webpage Loaded</p>
  </div>
</body>
</html>
)rawliteral";

// Handle homepage request
void handleRoot() {
  server.send_P(200, "text/html", webpage);
}

// Start the web server
void startWebServer() {
  server.on("/", handleRoot);

  server.begin();

  Serial.println("Web server started");
  Serial.println("Open the ESP32 IP address in your browser");
}

// Handle browser requests
void handleWebServer() {
  server.handleClient();
}

Below is the Code for INO file

// ********************************************************************************************//
// ** Program to Connect to Wifi network and display status and IP Address on Serial Monitor **//
//*********************************************************************************************//

#include <WiFi.h>
#include "WebServerCode.h"

// Wi-Fi credentials
const char* ssid = "";
const char* password = "";

void setup() {
  Serial.begin(115200);

  Serial.println();
  Serial.println("ESP32 Web Server - Stage 3");

  // Connect to Wi-Fi
  WiFi.begin(ssid, password);

  Serial.print("Connecting to Wi-Fi");

  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }

  Serial.println();
  Serial.println("Wi-Fi Connected!");
  Serial.print("IP Address: ");
  Serial.println(WiFi.localIP());

  // Start the web server
  startWebServer();
}

void loop() {
  // Handle incoming browser requests
  handleWebServer();
}

Below is the code for WebServerCode.h

// ************************************************************//
// This file contains function declarations for webserver code //
//************************************************************//

#ifndef WEB_SERVER_CODE_H
#define WEB_SERVER_CODE_H

void startWebServer();
void handleWebServer();

#endif

Stage 3 – Controlling an LED Using a Smartphone

In the final stage, we extend the webpage to control an LED connected to GPIO 25.

We add two buttons to the webpage:

  • LED ON
  • LED OFF

When the LED ON button is pressed, the browser sends an HTTP request to the ESP32 using the /led/on route.

The ESP32 receives the request and executes:

digitalWrite(ledPin, HIGH);

This switches ON the LED.

Similarly, when the LED OFF button is pressed, the browser sends a request to /led/off.

The ESP32 executes:

digitalWrite(ledPin, LOW);

This switches OFF the LED.

The ESP32 sends the current LED status back to the browser, and the webpage updates its status message.

Below is the code for update WebServerCode.cpp. Other 2 files remains unchanged.

#include <Arduino.h>
#include <WebServer.h>

#include "WebServerCode.h"

// LED configuration
const int ledPin = 25;

// Create web server on port 80
WebServer server(80);

// Webpage HTML
const char webpage[] PROGMEM = R"rawliteral(
<!DOCTYPE html>
<html>
<head>
  <title>ESP32 LED Control</title>

  <meta name="viewport"
        content="width=device-width, initial-scale=1">

  <style>
    body {
      font-family: Arial, sans-serif;
      text-align: center;
      background-color: #f2f2f2;
      margin-top: 40px;
    }

    h1 {
      color: #0066cc;
    }

    .box {
      background: white;
      padding: 25px;
      margin: 20px auto;
      max-width: 350px;
      border-radius: 12px;
      box-shadow: 0 2px 8px #cccccc;
    }

    button {
      padding: 15px 30px;
      font-size: 18px;
      margin: 10px;
      border: none;
      border-radius: 8px;
      color: white;
      cursor: pointer;
    }

    .on {
      background-color: #28a745;
    }

    .off {
      background-color: #dc3545;
    }

    #status {
      font-size: 20px;
      font-weight: bold;
    }
  </style>
</head>

<body>
  <div class="box">
    <h1>ESP32 LED Control</h1>

    <p>Control the LED using your smartphone.</p>

    <p id="status">LED Status: OFF</p>

    <button class="on" onclick="controlLED('on')">
      LED ON
    </button>

    <button class="off" onclick="controlLED('off')">
      LED OFF
    </button>

    <p id="message"></p>
  </div>

  <script>
    function controlLED(state) {
      fetch('/led/' + state)
        .then(response => response.text())
        .then(data => {
          document.getElementById('status').innerHTML =
            'LED Status: ' + data;

          document.getElementById('message').innerHTML =
            'Command sent successfully';
        })
        .catch(error => {
          document.getElementById('message').innerHTML =
            'Connection error';
        });
    }
  </script>
</body>
</html>
)rawliteral";

// Display the webpage
void handleRoot() {
  server.send_P(200, "text/html", webpage);
}

// Turn LED ON
void handleLEDOn() {
  digitalWrite(ledPin, HIGH);

  server.send(200, "text/plain", "ON");
}

// Turn LED OFF
void handleLEDOff() {
  digitalWrite(ledPin, LOW);

  server.send(200, "text/plain", "OFF");
}

// Start the web server
void startWebServer() {
  // Configure LED pin
  pinMode(ledPin, OUTPUT);
  digitalWrite(ledPin, LOW);

  // Webpage route
  server.on("/", handleRoot);

  // LED control routes
  server.on("/led/on", handleLEDOn);
  server.on("/led/off", handleLEDOff);

  // Start server
  server.begin();

  Serial.println("Web server started");
  Serial.println("Open the ESP32 IP address in your browser");
}

// Handle browser requests
void handleWebServer() {
  server.handleClient();
}

GitHub Link for complete code – https://github.com/pintushaw/ESP32BeginnerSeries_WebServer

How the Project Works

The overall working process is:

  1. ESP32 connects to the Wi-Fi router.
  2. Router assigns an IP address to the ESP32.
  3. User opens the ESP32 IP address in a smartphone browser.
  4. ESP32 sends the HTML webpage to the browser.
  5. User presses LED ON or LED OFF.
  6. Browser sends an HTTP request to the ESP32.
  7. ESP32 changes the GPIO 25 output.
  8. LED switches ON or OFF and the webpage updates its status.

Important Notes

  • The smartphone and ESP32 must be connected to the same local Wi-Fi network.
  • The original ESP32 DevKit V1 supports 2.4 GHz Wi-Fi.
  • The IP address may change when the ESP32 reconnects to the router.
  • The web server uses port 80 for HTTP communication.
  • This demonstration is designed for a local network and does not provide secure internet access to the device.

Project Demonstration

After completing all three stages, we can control the LED wirelessly using a smartphone. Open the ESP32 IP address in the browser, press LED ON and observe the LED lighting up. Press LED OFF to switch it off.

This demonstrates how an ESP32 can host its own webpage and receive commands over Wi-Fi.

Conclusion

In this project, we learned how to connect an ESP32 to Wi-Fi, create a web server, host a webpage and control an LED using a smartphone browser.

We also learned how to organize Arduino code into separate .ino, .h and .cpp files.

This project provides a foundation for more advanced ESP32 applications such as home automation, wireless sensor monitoring, remote device control and IoT projects.

Watch the complete project demonstration:

https://www.youtube.com/watch?v=LDCE4pCuu54

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.