ESP32 & IoTIntermediate

Build a Wi-Fi Web Server with ESP32

Create a web server on ESP32 that lets you control LEDs from any browser on your local network.

12 January 202612 min read

Introduction

The ESP32 has built-in Wi-Fi, making it perfect for IoT projects. In this tutorial, you'll create a web server that controls two LEDs from any browser on your local network.

Components Required

  • ESP32 development board
  • 2× LEDs
  • 2× 220Ω resistors
  • Breadboard and jumper wires

Wiring

  • LED 1: Pin 26 → 220Ω → LED → GND
  • LED 2: Pin 27 → 220Ω → LED → GND

The Code

#include <WiFi.h>

const char* ssid = "YOUR_WIFI_SSID";
const char* password = "YOUR_WIFI_PASSWORD";

WiFiServer server(80);

const int led1 = 26;
const int led2 = 27;

void setup() {
  Serial.begin(115200);
  pinMode(led1, OUTPUT);
  pinMode(led2, OUTPUT);

  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println("\nConnected! IP: " + WiFi.localIP().toString());
  server.begin();
}

void loop() {
  WiFiClient client = server.available();
  if (!client) return;

  String request = client.readStringUntil('\r');
  client.flush();

  if (request.indexOf("/led1/on") != -1) digitalWrite(led1, HIGH);
  if (request.indexOf("/led1/off") != -1) digitalWrite(led1, LOW);
  if (request.indexOf("/led2/on") != -1) digitalWrite(led2, HIGH);
  if (request.indexOf("/led2/off") != -1) digitalWrite(led2, LOW);

  String html = "<!DOCTYPE html><html><head>";
  html += "<meta name='viewport' content='width=device-width'>";
  html += "<style>body{font-family:sans-serif;text-align:center;padding:20px}";
  html += ".btn{padding:15px 30px;margin:10px;font-size:18px;border:none;";
  html += "border-radius:8px;cursor:pointer;color:white}";
  html += ".on{background:#22c55e}.off{background:#ef4444}</style></head>";
  html += "<body><h1>ESP32 LED Control</h1>";
  html += "<p>LED 1</p>";
  html += "<a href='/led1/on'><button class='btn on'>ON</button></a>";
  html += "<a href='/led1/off'><button class='btn off'>OFF</button></a>";
  html += "<p>LED 2</p>";
  html += "<a href='/led2/on'><button class='btn on'>ON</button></a>";
  html += "<a href='/led2/off'><button class='btn off'>OFF</button></a>";
  html += "</body></html>";

  client.println("HTTP/1.1 200 OK");
  client.println("Content-Type: text/html");
  client.println();
  client.println(html);
  client.stop();
}

How It Works

  1. ESP32 connects to your Wi-Fi network
  2. It starts a web server on port 80
  3. When you visit the ESP32's IP address in a browser, you see ON/OFF buttons
  4. Clicking a button sends a request like /led1/on that toggles the LED

Testing

Upload the code, open Serial Monitor, note the IP address. Open that IP in your phone or computer browser and control the LEDs!

Tags:ESP32Wi-FiWeb Server