ESP32 Masterclass: Create and Control Your Own Web Server for LED On/Off | Trending IoT Tutorial

ESP32 Masterclass: Create and Control Your Own Web Server for LED On/Off | Trending IoT Tutorial

ESP32 Projects IoT Tutorials Web Server Projects Home Automation



Welcome to YaranaIoT Guru’s ESP32 Masterclass! In this tutorial, we’ll teach you how to create a web server on ESP32 and control an LED remotely via your web browser.

ESP32 is a powerful microcontroller with built-in Wi-Fi, making it perfect for IoT and web-based projects. By the end of this guide, you’ll have a fully functional IoT setup, capable of controlling LEDs, relays, or other appliances.


🔹 Why ESP32 Web Server Projects?

  • Control devices remotely via any browser
  • Learn the fundamentals of IoT programming and networking
  • Easy integration with home automation systems
  • Great for beginner to advanced IoT enthusiasts

🔹 Project Goals

  1. Set up ESP32 and Arduino IDE for web server development
  2. Create a simple web page hosted on ESP32
  3. Control an LED from the web page
  4. Understand Wi-Fi connection, IP addressing, and HTTP requests
  5. Expandable to multiple LEDs or appliances

🔹 Applications

  • LED control for learning IoT basics
  • Home automation for lights and fans
  • IoT workshops and educational projects
  • Remote control of small appliances via Wi-Fi

🔹 Required Components

ComponentQuantityDescription
ESP32 Dev Board1Microcontroller with Wi-Fi
LED1Output indicator
220Ω Resistor1Current limiting for LED
Breadboard & Jumper WiresAs neededCircuit connections
USB Cable1ESP32 power and programming
PC with Arduino IDE1Development environment

🔹 Circuit Diagram

Connections:

  • LED → GPIO2 (D2)
  • Resistor (220Ω) in series with LED to GND
  • ESP32 powered via USB

Simple circuit allows you to test web-based control of a single LED, but it can be extended to relays, motors, or multiple LEDs.

🔹 Step 1: Arduino IDE Setup

  1. Install the latest Arduino IDE from https://www.arduino.cc/en/software
  2. Add ESP32 board support:
    • Go to File → Preferences → Additional Board Manager URLs
    • Add: https://dl.espressif.com/dl/package_esp32_index.json
    • Go to Tools → Board → Board Manager, search ESP32, and install
  3. Select your ESP32 board:
    • Tools → Board → ESP32 Dev Module
    • Select correct COM port for your ESP32

🔹 Step 2: Connect ESP32 to Wi-Fi

We need Wi-Fi to serve the web page. Include these libraries in your code:

#include <WiFi.h>

const char* ssid = "YourWiFiName";
const char* password = "YourWiFiPassword";

In setup(), connect to Wi-Fi:

void setup() {
  Serial.begin(115200);
  WiFi.begin(ssid, password);
  
  Serial.print("Connecting to WiFi");
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  
  Serial.println("");
  Serial.println("WiFi connected!");
  Serial.print("ESP32 IP Address: ");
  Serial.println(WiFi.localIP());
}

✅ The serial monitor will display your ESP32 IP address, which you will use to access the web server.


🔹 Step 3: Create a Basic Web Server

ESP32 can act as a web server using the WiFi.h library. Here’s the full code to control an LED on GPIO2:

#include <WiFi.h>

const char* ssid = "YourWiFiName";
const char* password = "YourWiFiPassword";

WiFiServer server(80); // Server on port 80
const int ledPin = 2;  // GPIO2 for LED

void setup() {
  Serial.begin(115200);
  pinMode(ledPin, OUTPUT);
  WiFi.begin(ssid, password);
  
  Serial.print("Connecting to WiFi");
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  
  Serial.println("");
  Serial.println("WiFi connected!");
  Serial.print("ESP32 IP Address: ");
  Serial.println(WiFi.localIP());
  
  server.begin();
}

void loop() {
  WiFiClient client = server.available();
  if (client) {
    Serial.println("New Client Connected");
    String request = client.readStringUntil('\r');
    Serial.println(request);
    client.flush();

    // Control LED based on HTTP request
    if (request.indexOf("/LED=ON") != -1) {
      digitalWrite(ledPin, HIGH);
    }
    if (request.indexOf("/LED=OFF") != -1) {
      digitalWrite(ledPin, LOW);
    }

    // HTML response
    client.println("HTTP/1.1 200 OK");
    client.println("Content-Type: text/html");
    client.println("Connection: close");
    client.println();
    client.println("<!DOCTYPE html>");
    client.println("<html>");
    client.println("<h1>ESP32 LED Control</h1>");
    client.println("<p><a href=\"/LED=ON\"><button>LED ON</button></a></p>");
    client.println("<p><a href=\"/LED=OFF\"><button>LED OFF</button></a></p>");
    client.println("</html>");
    
    delay(1);
    Serial.println("Client disconnected");
  }
}

🔹 Step 4: Access the Web Server

  1. Upload the code to ESP32
  2. Open Serial Monitor → note the IP address
  3. Enter the IP in your browser → you will see LED ON/OFF buttons
  4. Click ON/OFF → LED should toggle

Tip: You can add more buttons and GPIO pins to control multiple LEDs or relays.


🔹 Step 5: Testing and Troubleshooting

  • Ensure Wi-Fi credentials are correct
  • Check GPIO connection for LED + resistor
  • Serial monitor helps debug client connections
  • Use different browsers or devices to test remote access

🔹 1. Controlling Multiple LEDs

Suppose you want to control 3 LEDs simultaneously. Here’s how to modify your code:

Connections:

LEDGPIO Pin
LED12
LED24
LED35

Code Example:

#include <WiFi.h>

const char* ssid = "YourWiFiName";
const char* password = "YourWiFiPassword";

WiFiServer server(80);

const int led1 = 2;
const int led2 = 4;
const int led3 = 5;

void setup() {
  Serial.begin(115200);
  pinMode(led1, OUTPUT);
  pinMode(led2, OUTPUT);
  pinMode(led3, OUTPUT);
  
  WiFi.begin(ssid, password);
  Serial.print("Connecting to WiFi");
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println("\nWiFi connected");
  Serial.print("IP Address: ");
  Serial.println(WiFi.localIP());
  
  server.begin();
}

void loop() {
  WiFiClient client = server.available();
  if (client) {
    String request = client.readStringUntil('\r');
    client.flush();
    
    // LED control
    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);
    if (request.indexOf("/LED3=ON") != -1) digitalWrite(led3, HIGH);
    if (request.indexOf("/LED3=OFF") != -1) digitalWrite(led3, LOW);
    
    // Dynamic HTML page
    client.println("HTTP/1.1 200 OK");
    client.println("Content-Type: text/html");
    client.println("Connection: close");
    client.println();
    client.println("<!DOCTYPE html>");
    client.println("<html>");
    client.println("<h1>ESP32 Multi-LED Control</h1>");
    client.println("<p><a href=\"/LED1=ON\"><button>LED1 ON</button></a> <a href=\"/LED1=OFF\"><button>LED1 OFF</button></a></p>");
    client.println("<p><a href=\"/LED2=ON\"><button>LED2 ON</button></a> <a href=\"/LED2=OFF\"><button>LED2 OFF</button></a></p>");
    client.println("<p><a href=\"/LED3=ON\"><button>LED3 ON</button></a> <a href=\"/LED3=OFF\"><button>LED3 OFF</button></a></p>");
    client.println("</html>");
    
    delay(1);
  }
}

✅ This allows simultaneous control of three LEDs with separate buttons on the same web page.


🔹 2. Real-Time LED Status Feedback

To improve the user experience, display the current LED state on the web page:

String ledState(int pin) {
  return digitalRead(pin) ? "ON" : "OFF";
}

Update HTML page dynamically:

client.println("<p>LED1 Status: " + ledState(led1) + "</p>");
client.println("<p>LED2 Status: " + ledState(led2) + "</p>");
client.println("<p>LED3 Status: " + ledState(led3) + "</p>");

Users can now see which LEDs are ON/OFF in real-time.


🔹 3. Mobile-Friendly Web Interface

Use simple CSS styles to make the page mobile-friendly:

client.println("<style>button {width:100px; height:50px; margin:5px; font-size:16px;} body {text-align:center; font-family:Arial;}</style>");
  • Buttons are larger and easier to tap
  • Works well on phones and tablets for IoT control

🔹 4. Advanced Features

  1. Timers & Scheduling
    • Turn LEDs ON/OFF at specific times
    • Use millis() or NTP time for automation
  2. Sensor Integration
    • Connect DHT11, PIR, or LDR sensors
    • Control LEDs based on sensor values (temperature, motion, or light)
  3. Multiple Device Support
    • Extend GPIO control to relays for home appliances
    • Use unique HTML buttons for each device
  4. Secure Access
    • Add a password check in your HTML form for private control
    • Prevent unauthorized users from toggling LEDs

🔹 5. Testing & Troubleshooting

  • Test with multiple devices: LED1, LED2, LED3
  • Check browser cache if buttons don’t respond
  • Verify ESP32 IP address is accessible on the network
  • Use Serial Monitor to debug HTTP requests

🔹 1. Real-Time IoT Feedback

With the web server running, you can display live feedback for LED status:

  • Update HTML dynamically with current LED states:
String ledState(int pin) {
  return digitalRead(pin) ? "ON" : "OFF";
}

client.println("<p>LED1 Status: " + ledState(led1) + "</p>");
client.println("<p>LED2 Status: " + ledState(led2) + "</p>");
client.println("<p>LED3 Status: " + ledState(led3) + "</p>");
  • Users can now monitor LED status in real-time, creating a professional IoT dashboard feel.

🔹 2. Integrating ESP32 with Cloud Services

For advanced IoT applications, integrate your ESP32 with cloud platforms like Firebase or Ubidots:

Example: Firebase Realtime Database Integration

  1. Include the HTTPClient library:
#include <WiFi.h>
#include <HTTPClient.h>
  1. Send LED state to Firebase:
if(WiFi.status()== WL_CONNECTED){
  HTTPClient http;
  String url = "https://your-project.firebaseio.com/led1.json";
  String payload = digitalRead(led1) ? "1" : "0";
  http.begin(url);
  http.PUT(payload);
  http.end();
}
  1. You can now control LEDs remotely from a mobile app and sync real-time feedback.

🔹 3. Scheduling & Timers

Use millis() or integrate NTP (Network Time Protocol) for automated tasks:

unsigned long previousMillis = 0;
const long interval = 5000; // 5 seconds

void loop() {
  unsigned long currentMillis = millis();
  if(currentMillis - previousMillis >= interval){
    previousMillis = currentMillis;
    digitalWrite(led1, !digitalRead(led1)); // Toggle LED1 every 5s
  }
}
  • Automates devices without manual intervention
  • Perfect for home automation or timed LED patterns

🔹 4. Adding Sensors to Your Web Server

Combine LEDs with sensor data to create responsive IoT systems:

Example: Light-Dependent LED Control with LDR Sensor

int ldrPin = 34; // ADC pin for LDR
int ldrValue;

void loop(){
  ldrValue = analogRead(ldrPin);
  if(ldrValue < 500){
    digitalWrite(led1, HIGH);
  } else {
    digitalWrite(led1, LOW);
  }
}
  • LED turns ON automatically in dark conditions
  • Web server still allows manual override via buttons

🔹 5. Security & Access Control

For public or shared networks:

  • Add password authentication on web pages
  • Use HTTPS (via ESP32 with SSL) for secure cloud communication
  • Prevent unauthorized access to IoT devices

🔹 6. Future Upgrades

  1. Mobile App Integration
    • Connect ESP32 to mobile apps like Blynk or custom Flutter apps
  2. Voice Assistant Control
    • Integrate with Google Assistant or Alexa for voice commands
  3. Data Logging
    • Save sensor readings and device status to cloud
    • Visualize with charts and graphs in real-time
  4. Multi-Device Networks
    • Control multiple ESP32 devices from a single web interface
    • Ideal for smart homes or classrooms
  5. OTA Updates
    • Enable Over-The-Air updates to upload new code remotely

🔹 7. Final Testing

  • Ensure all LEDs respond via web buttons and cloud commands
  • Test real-time feedback on multiple devices
  • Validate timers, automation, and sensor-triggered actions
  • Check Wi-Fi reliability for smooth operation

🔹 Conclusion

By following this ESP32 web server masterclass, you have achieved:

  1. Web-based control of single and multiple LEDs
  2. Real-time IoT feedback for LED status
  3. Integration with cloud platforms like Firebase
  4. Timers, sensors, and automated actions for smart applications
  5. Knowledge to expand into full home automation systems

“Creating your own web server on ESP32 is the foundation of modern IoT projects — controlling devices remotely, monitoring in real-time, and integrating with the cloud for endless possibilities.”
YaranaIoT Guru

📞 Contact YaranaIoT Guru Empowering IoT Innovation | ESP32 | Home Automation | Smart Solutions | 50K+ Community

We’d love to hear from you! Whether it’s IoT project queries, collaborations, tech support, custom PCB design, bulk orders, corporate training, college workshops, or freelance development — we’re just one message away.


✉️ Email (Official)

For detailed inquiries, project support, business collaboration, sponsorships, or documentation: 📩 contact@yaranaiotguru.in 📧 Alternate: support@yaranaiotguru.inResponse: Within 24 hours (Mon–Sat) 💡 Best for attachments (code, schematics, logs, etc.)


📱 Phone / WhatsApp (24×7 Support)

Instant live help, troubleshooting, project consultation, or order updates: 📞 +91 70527 22734 💬 WhatsApp: Chat NowCall Hours: Mon–Sat, 10 AM – 7 PM IST 🚀 Emergency? WhatsApp anytime — reply within 1 hour


🌐 Official Website

Tutorials, code, PDFs, schematics, blogs, free tools & online store: 🔗 www.yaranaiotguru.in 🛒 Shop: yaranaiotguru.in/shop (ESP32 DevKits, Sensors, Relays, Custom PCBs, Project Kits)


▶️ YouTube Channel

Step-by-step IoT builds, live coding, ESP32, Blynk, Node-RED, MQTT, Home Assistant & more: 🔗 Yarana IoT Guru 📺 1,200+ Videos | 52K+ Subs | 5.5M+ Views | 4.8★ Rating 🎥 New Video Every Week — 🔔 Subscribe & Turn On Notifications


🛠 GitHub (100% Open Source)

All codes, Arduino sketches, PlatformIO projects, Node-RED flows, MQTT configs & docs: 🔗 github.com/YaranaIotGuru50+ Repos | 10K+ Stars & Forks

🔥 Top Projects:

  • ESP32 WebSocket Real-Time Dashboard
  • Smart Home with Blynk & Alexa
  • IoT Irrigation System with Soil Moisture
  • MQTT + Node-RED + MySQL Logging
  • OLED Weather Station with API

📸 Instagram

Daily reels, quick tips, live builds, student showcases & giveaways: 🔗 @YaranaIoTGuru 📱 10K+ Followers | Reels | Stories | Live Sessions


💼 LinkedIn (Professional Network)

B2B, IoT consulting, training, hiring & partnerships: 🔗 Yarana IoT Guru

🤝 Services Offered:

  • Custom IoT Product Development
  • Embedded Systems Training
  • College Workshops & FDPs
  • PCB Design & Prototyping

🐦 Twitter / X

Real-time updates, polls, project launches & community Q&A: 🔗 @YaranaIoTGuru 📢 Follow for instant alerts


🛠 Hackster.io (Project Showcases)

In-depth write-ups, circuits, BOM, code & ratings: 🔗 hackster.io/yaranaiotguru 🏆 50+ Projects | 100K+ Views | Top 5% Creator


📝 Instructables (DIY Guides)

Beginner-friendly step-by-step guides with templates & troubleshooting: 🔗 instructables.com/member/YaranaIoTGuru

🛠 Featured Guides:

  • Automatic Plant Watering System
  • Voice-Controlled Home Appliances
  • WiFi-enabled Temperature Monitor

📚 Medium Blog

Deep-dive articles, trends, tutorials & career tips in embedded systems: 🔗 medium.com/@yaranaiotguru ✍️ 50+ Articles | 15K+ Readers


🛒 Online Store & Kits

Ready-to-use IoT kits, custom PCBs, sensors & merch: 🔗 yaranaiotguru.in/shop 📦 Free Shipping in India above ₹999 💳 Payment: UPI, Card, Wallet, COD


🌟 Community Platforms

PlatformLinkPurpose
Telegram Channelt.me/YaranaIoTGuruProject files, PDFs, updates
Telegram Groupt.me/YaranaIoTCommunityPeer support, doubts
Discord Serverdiscord.gg/yarana-iotLive voice help, coding rooms
WhatsApp CommunityJoin HereAnnouncements & polls

🏢 Office & Studio Address

Yarana Studio & Software (Yarana IoT Guru HQ) 📍 Near Rookh Baba Mandir, Umariya Badal Urf Gainda, Allahabad (Prayagraj), Uttar Pradesh – 212507, India ⭐ Google Rating: 5.0 ★ (100+ Reviews)

🕒 Opening Hours: Mon–Sat: 10:00 AM – 5:00 PM Sunday: Closed

🌐 Associated Website: yaranawebtech.in 🗺️ View on Google Maps: Search “Yarana Studio & Software” 📌 Walk-ins welcome | Appointment recommended for project discussions

Leave a Reply

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