DIYables ESP32 Web Server Example

WebServer Example - Multi-Page Web Server

Overview

This example demonstrates how to create a multi-page web server on ESP32 with multiple interconnected pages for home, temperature monitoring, and LED control.

Features

  • Multi-page navigation with seamless page transitions
  • Home page with navigation menu and system information
  • Temperature monitoring page with real-time temperature display and refresh capability
  • LED control page with ON/OFF toggle functionality
  • Template-based HTML with dynamic content replacement
  • Helper functions for clean, maintainable code

Hardware Used In This Tutorial

1×ESP-WROOM-32 Dev Module
1×USB Cable Type-A to Type-C (for USB-A PC)
1×USB Cable Type-C to Type-C (for USB-C PC)
1×Recommended: Screw Terminal Expansion Board for ESP32
1×Recommended: Breakout Expansion Board for ESP32
1×Recommended: Power Splitter for ESP32

Or you can buy the following kits:

1×DIYables ESP32 Starter Kit (ESP32 included)
1×DIYables Sensor Kit (30 sensors/displays)
1×DIYables Sensor Kit (18 sensors/displays)
Disclosure: Some of the links in this section are Amazon affiliate links, meaning we may earn a commission at no additional cost to you if you make a purchase through them. Additionally, some links direct you to products from our own brand, DIYables .

Library Installation

Follow these instructions step by step:

  • If this is your first time using the ESP32, refer to the tutorial on setting up the environment for ESP32 in the Arduino IDE.
  • Connect the ESP32 board to your computer using a USB cable.
  • Launch the Arduino IDE on your computer.
  • Select the appropriate ESP32 board (e.g., ESP32) and COM port.
  • Open the Library Manager by clicking on the Library Manager icon on the left side of the Arduino IDE.
  • Search for Web Server for ESP32 and locate the mWebSockets by DIYables.
  • Click on the Install button to add the mWebSockets library.
ESP32 Web Server library

Web Server Example

  • On Arduino IDE, Go to File Examples Web Server for ESP32 WebServer example to open the example code

Circuit Connection

No external components required - this example uses the built-in LED on pin 13.

Code Structure

  1. home.h: Home page HTML template
  2. temperature.h: Temperature monitoring page template
  3. led.h: LED control page template
  4. WebServer.ino: Main server logic

Setup Instructions

1. Network Configuration

Edit the WiFi credentials directly in the WebServer.ino file:

const char WIFI_SSID[] = "YOUR_WIFI_SSID"; const char WIFI_PASSWORD[] = "YOUR_WIFI_PASSWORD";

2. Upload Code and Monitor Output

  1. Connect your ESP32 to your computer
  2. Select the correct board and port in Arduino IDE
  3. Upload the WebServer.ino sketch
  4. Open Serial Monitor (9600 baud)
  5. Wait for WiFi connection
  6. Note the IP address displayed
  7. If you do not see IP address in Serial monitor, press the reset button on the ESP32 board

Usage

Open your web browser and enter the IP address displayed in the Serial Monitor to access the ESP32 Web Server.

ESP32 Web Server

Test the Temperature Monitoring Function:

  • Click on the "Temperature" menu.
  • View the temperature display.
ESP32 Web Server Temperature

Test the LED Control Function:

  • Click on the "LED Control" menu. You will see the web interface like the below:
LED Control Page Demo
  • Toggle the LED ON and OFF using the provided buttons.
  • Observe the built-in LED status on the ESP32 board update instantly.

Available Pages

Home Page (`/`)
  • URL: http://your-esp32-ip/
  • Features:
    • Welcome message with system information
    • Navigation menu to all pages
    • Clean, professional layout
    Temperature Page (`/temperature`)
    • URL: http://your-esp32-ip/temperature
    • Features:
      • Real-time temperature display in Celsius
      • Auto-refresh every 5 seconds
      • Manual refresh button
      • Back to home navigation
      LED Control Page (`/led`)
      • URL: http://your-esp32-ip/led
      • ON URL: http://your-esp32-ip/led/on
      • OFF URL: http://your-esp32-ip/led/off
      • Features:
        • Current LED status display
        • Separate routes for ON and OFF actions
        • Immediate status updates after state change
        • Back to home navigation

        Code Explanation

        Server Routes

        // Configure routes with custom handler functions server.addRoute("/", handleHome); server.addRoute("/temperature", handleTemperature); server.addRoute("/led", handleLed); server.addRoute("/led/on", handleLedOn); server.addRoute("/led/off", handleLedOff); // Handler function examples void handleHome(WiFiClient& client, const String& method, const String& request, const QueryParams& params, const String& jsonData) { server.sendResponse(client, HOME_PAGE); } void handleTemperature(WiFiClient& client, const String& method, const String& request, const QueryParams& params, const String& jsonData) { float tempC = 25.5; // Simulated temperature value String response = TEMPERATURE_PAGE; response.replace("%TEMP_C%", String(tempC, 1)); server.sendResponse(client, response.c_str()); } void handleLedOn(WiFiClient& client, const String& method, const String& request, const QueryParams& params, const String& jsonData) { ledState = HIGH; digitalWrite(LED_PIN, ledState); sendLedPage(client); } void handleLedOff(WiFiClient& client, const String& method, const String& request, const QueryParams& params, const String& jsonData) { ledState = LOW; digitalWrite(LED_PIN, ledState); sendLedPage(client); }

        Template System

        The example uses a placeholder replacement system for dynamic content:

        • %TEMP_C%: Replaced with current temperature value in Celsius
        • %LED_STATUS%: Replaced with current LED status ("ON" or "OFF")

        Helper Functions

        // Helper function to send LED page with current status void sendLedPage(WiFiClient& client) { String ledStatus = (ledState == HIGH) ? "ON" : "OFF"; String response = LED_PAGE; response.replace("%LED_STATUS%", ledStatus); server.sendResponse(client, response.c_str()); } // LED state tracking int ledState = LOW; // Track LED state (LOW = OFF, HIGH = ON)

        Customization

        Adding New Pages

        1. Create HTML template in new header file
        2. Add route handler in main loop
        3. Update navigation menu in existing pages

        Styling

        Modify the CSS in HTML templates to change appearance:

        <style> body { font-family: Arial, sans-serif; margin: 40px; } .container { max-width: 600px; margin: 0 auto; } /* Add your custom styles here */ </style>

        Adding Sensors

        Replace the simulated temperature value with real sensor readings:

        void handleTemperature(WiFiClient& client, const String& method, const String& request, const QueryParams& params, const String& jsonData) { // Replace with actual sensor reading // e.g., DHT22, DS18B20, etc. float tempC = readActualTemperatureSensor(); // Your sensor function here String response = TEMPERATURE_PAGE; response.replace("%TEMP_C%", String(tempC, 1)); server.sendResponse(client, response.c_str()); }

        Troubleshooting

        Common Issues

        WiFi Connection Failed

        • Verify SSID and password in the WebServer.ino file
        • Check WiFi network availability
        • Ensure ESP32 is within WiFi range

        Pages Not Loading

        • Check Serial Monitor for IP address
        • Verify browser URL matches ESP32's IP Address
        • Try refreshing the page

        LED Not Responding

        • Confirm LED is connected to pin 13
        • Check Serial Monitor for debug messages
        • Verify route handlers are registered

        Debug Output

        Enable additional debugging by adding Serial.println() statements:

        void handleLed(WiFiClient& client, const String& method, const String& request, const QueryParams& params, const String& jsonData) { Serial.println("LED route accessed"); Serial.println("Method: " + method); Serial.println("Request: " + request); sendLedPage(client); }

        Next Steps

        • Explore the WebServerJson.ino example for REST API development
        • Try WebServerQueryStrings.ino for advanced parameter handling
        • Check out WebServerWithWebSocket.ino for real-time communication

        Learning Resources

※ OUR MESSAGES