Table of Contents

In the ESP32, hosting a web server is straightforward, allowing us to display data from the ESP32, such as sensor information, or even gather input from users. In this chapter, we will explore the capabilities of the ESP32 web server and its potential applications.

Create a new sketch and save it as “Web_Server.” In the Sketch menu, select “Add File” and add the “WiFiHelper.ino” file that we created in the WiFi Station Mode chapter. This will copy the file into the current sketch folder, and you should see it appear in the current tab. To verify, click “Show Sketch Folder” in the Sketch menu.

Verify that the ESP32 can connect to your local WiFi by using the following basic code. You can view the ESP32’s IP address in the Arduino Serial Monitor.

void setup() {

    Serial.begin(115200);
    connectToWiFi();

}

void loop() {

}

Let’s set up a web server. When a client accesses the ESP32’s homepage, it will display “Lonely Binary.”

#include <WebServer.h>

//WebServer run at default HTTP Port 80
WebServer webServer(80);

// HTML content
const char* htmlContent = "<h1>Lonely Binary</h1>";

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

    // Serve the HTML page
    webServer.on("/", HTTP_GET, [](){
        webServer.send(200, "text/html", htmlContent);
    });

    webServer.begin(); // Start the server
}



void loop() {
    webServer.handleClient(); // Handle incoming client requests
}

This code is for setting up a basic HTTP web server using the WebServer library on an ESP32. Here’s a breakdown of the code:

#include <WebServer.h>

This line includes the WebServer library, which is used to create and handle the web server. This library simplifies setting up a web server on ESP32.

WebServer webServer(80);

This creates an instance of the WebServer class and sets it to listen on port 80, the default port for HTTP.

const char* htmlContent = "<h1>Lonely Binary</h1>";

Here, a simple HTML string is defined. This will be the content served when a client accesses the server.

webServer.on("/", HTTP_GET, []() {}

This line tells the server to respond to HTTP GET requests sent to the root URL (/). It’s a route that responds to the browser’s request for the homepage.

webServer.send(200, "text/html", htmlContent);

The server responds by sending the htmlContent we defined earlier with HTTP status code 200 (OK).

webServer.begin();

This starts the web server, making it ready to accept incoming requests.

webServer.handleClient();

In the loop, this function constantly monitors for incoming client requests and processes them. When a request is received, it handles the request, triggers the corresponding route (like the one defined in the setup), and sends a response back to the client.

Open a browser and go to http://ESP32-IP-Address. The browser will display the HTML content defined in the htmlContent variable, which shows Lonely Binary as the headline.

Categorized in:

Web Server,

Tagged in: