Embedded System Project 8: ESP32 Web Server

Fernaldi Fauzie
9 min readMar 23, 2021

Hello! This time, in this story we will play with an ESP32 web server. We will try to create a standalone web server with an ESP32 that controls outputs of 2 LEDs using the Arduino IDE programming environment. This web server is mobile responsive and can be accessed with any device that as a browser on the local network.

As usual, before we continue, I would like to tell you guys that we will use this randomnerdtutorials link as a reference.

Components and Parts Required

For this story, we will need:

  • ESP32 Board
  • 2x 5mm LED
  • 2x 330 Ohm resistor
  • Jumper wires (I’m using male to male jumper wires)
  • Breadboard
  • Any device that as a browser on the local network

Schematic Diagram

First, we have to build the circuit. The first LED connected to GPIO19 and the other one connected to GPIO21.

My Circuit

Code

Next, we can start with the code. You may copy the following code to your Arduino IDE, but don’t upload it immediately! We need to change some things to make it work!

/*********
This code is referencing to: Rui Santos
More details at https://randomnerdtutorials.com
*********/
// Load Wi-Fi library
#include <WiFi.h>
// Replace with your network credentials
const char* ssid = "FF";
const char* password = "anrq8199";
// Set web server port number to 80
WiFiServer server(80);
// Variable to store the HTTP request
String header;
// Auxiliar variables to store the current output state
String output19State = "off";
String output21State = "off";
// Assign output variables to GPIO pins
const int output19 = 19;
const int output21 = 21;
// Current time
unsigned long currentTime = millis();
// Previous time
unsigned long previousTime = 0;
// Define timeout time in milliseconds (example: 2000ms = 2s)
const long timeoutTime = 2000;
void setup() {
Serial.begin(115200);
// Initialize the output variables as outputs
pinMode(output19, OUTPUT);
pinMode(output21, OUTPUT);
// Set outputs to LOW
digitalWrite(output19, LOW);
digitalWrite(output21, LOW);
// Connect to Wi-Fi network with SSID and password
Serial.print("Connecting to ");
Serial.println(ssid);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
// Print local IP address and start web server
Serial.println("");
Serial.println("WiFi connected.");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
server.begin();
}
void loop(){
WiFiClient client = server.available(); // Listen for incoming clients
if (client) { // If a new client connects,
currentTime = millis();
previousTime = currentTime;
Serial.println("New Client."); // print a message out in the serial port
String currentLine = ""; // make a String to hold incoming data from the client
while (client.connected() && currentTime - previousTime <= timeoutTime) { // loop while the client's connected
currentTime = millis();
if (client.available()) { // if there's bytes to read from the client,
char c = client.read(); // read a byte, then
Serial.write(c); // print it out the serial monitor
header += c;
if (c == '\n') { // if the byte is a newline character
// if the current line is blank, you got two newline characters in a row.
// that's the end of the client HTTP request, so send a response:
if (currentLine.length() == 0) {
// HTTP headers always start with a response code (e.g. HTTP/1.1 200 OK)
// and a content-type so the client knows what's coming, then a blank line:
client.println("HTTP/1.1 200 OK");
client.println("Content-type:text/html");
client.println("Connection: close");
client.println();

// turns the GPIOs on and off
if (header.indexOf("GET /19/on") >= 0) {
Serial.println("GPIO 19on");
output19State = "on";
digitalWrite(output19, HIGH);
} else if (header.indexOf("GET /19/off") >= 0) {
Serial.println("GPIO 19off");
output19State = "off";
digitalWrite(output19, LOW);
} else if (header.indexOf("GET /21/on") >= 0) {
Serial.println("GPIO 21 on");
output21State = "on";
digitalWrite(output21, HIGH);
} else if (header.indexOf("GET /21/off") >= 0) {
Serial.println("GPIO 21 off");
output21State = "off";
digitalWrite(output21, LOW);
}

// Display the HTML web page
client.println("<!DOCTYPE html><html>");
client.println("<head><meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">");
client.println("<link rel=\"icon\" href=\"data:,\">");
// CSS to style the on/off buttons
// Feel free to change the background-color and font-size attributes to fit your preferences
client.println("<style>html { font-family: courier; display: inline-block; margin: 0px auto; text-align: center; color: white; background-color: black;}");
client.println(".button { background-color: #45E6A3; border: none; color: black; padding: 16px 40px;");
client.println("text-decoration: none; font-size: 30px; margin: 2px; cursor: pointer;}");
client.println(".button2 {background-color: #DEDEDE;}</style></head>");

// Web Page Heading
client.println("<body><h1>ESP32 Web Server</h1>");

// Display current state, and ON/OFF buttons for GPIO 19
client.println("<p>GPIO 19- State " + output19State + "</p>");
// If the output19State is off, it displays the ON button
if (output19State=="off") {
client.println("<p><a href=\"/19/on\"><button class=\"button\">ON</button></a></p>");
} else {
client.println("<p><a href=\"/19/off\"><button class=\"button button2\">OFF</button></a></p>");
}

// Display current state, and ON/OFF buttons for GPIO 21
client.println("<p>GPIO 21 - State " + output21State + "</p>");
// If the output21State is off, it displays the ON button
if (output21State=="off") {
client.println("<p><a href=\"/21/on\"><button class=\"button\">ON</button></a></p>");
} else {
client.println("<p><a href=\"/21/off\"><button class=\"button button2\">OFF</button></a></p>");
}
client.println("</body></html>");

// The HTTP response ends with another blank line
client.println();
// Break out of the while loop
break;
} else { // if you got a newline, then clear currentLine
currentLine = "";
}
} else if (c != '\r') { // if you got anything else but a carriage return character,
currentLine += c; // add it to the end of the currentLine
}
}
}
// Clear the header variable
header = "";
// Close the connection
client.stop();
Serial.println("Client disconnected.");
Serial.println("");
}
}

The part of the code we should modify are these:

// Replace with your network credentials
const char* ssid = "REPLACE_WITH_YOUR_SSID";
const char* password = "REPLACE_WITH_YOUR_PASSWORD";

To find your SSID, it’s pretty simple. In Windows, just click on the Wi-Fi icon located on the bottom right corner, and then click Properties on your network. For others like macOS, Android, and iOS, you may check this link.

Next, we can upload the code. After that, when you see the dot, press the ESP32 button (reset) to connects with Wi-Fi and outputs the ESP32 IP address on the Serial Monitor.

Then, open your browser, then copy your ESP32 IP address to the browser. In my case, it’s 192.168.43.248, and here is the result:

At the Serial Monitor in Arduino IDE, we can see what’s happening on the background. The ESP32 receives an HTTP request from a new client. In this case, the client is the browser.

Also, you may see other information about the HTTP request.

Testing the Web Server

Turning on and off the LEDs

Fortunately, everything went well! When we press the ON button, it will turn on the corresponding LED with the GPIO that is written on the screen. Then, the state will change from off to on, and the ON button will change to OFF button.

Code Explanation

I would like to outline some parts of the code, especially the one that still new in our stories!

The following line is to include the WiFi library.

#include <WiFi.h>

This one set the web server to port 80.

WiFiServer server(80);

Next, this one creates a variable to store the header of the HTTP request

String header;

setup() Section

Next, we have the setup(). This one is to begin the Wi-Fi connection with WiFi.begin(ssid, password) function, wait for the successful connection and print the ESP IP address in the Serial Monitor.

// Connect to Wi-Fi network with SSID and password
Serial.print("Connecting to ");
Serial.println(ssid);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
// Print local IP address and start web server
Serial.println("");
Serial.println("WiFi connected.");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
server.begin();

loop() Section

Then, we will have the loop() section. In short, we program what happens when a new client (in this case is browser) establishes a connection with the web server. Example: Control the outputs accordingly when the button is pressed on your web page.

We can make the ESP32always listening for incoming clients with the following line:

WiFiClient client = server.available(); // Listen for incoming clients

Keep in mind that you should only change this code if you know what you’re doing!

void loop(){
WiFiClient client = server.available(); // Listen for incoming clients
if (client) { // If a new client connects,
currentTime = millis();
previousTime = currentTime;
Serial.println("New Client."); // print a message out in the serial port
String currentLine = ""; // make a String to hold incoming data from the client
while (client.connected() && currentTime - previousTime <= timeoutTime) { // loop while the client's connected
currentTime = millis();
if (client.available()) { // if there's bytes to read from the client,
char c = client.read(); // read a byte, then
Serial.write(c); // print it out the serial monitor
header += c;
if (c == '\n') { // if the byte is a newline character
// if the current line is blank, you got two newline characters in a row.
// that's the end of the client HTTP request, so send a response:
if (currentLine.length() == 0) {
// HTTP headers always start with a response code (e.g. HTTP/1.1 200 OK)
// and a content-type so the client knows what's coming, then a blank line:
client.println("HTTP/1.1 200 OK");
client.println("Content-type:text/html");
client.println("Connection: close");
client.println();

// turns the GPIOs on and off
if (header.indexOf("GET /19/on") >= 0) {
Serial.println("GPIO 19on");
output19State = "on";
digitalWrite(output19, HIGH);
} else if (header.indexOf("GET /19/off") >= 0) {
Serial.println("GPIO 19off");
output19State = "off";
digitalWrite(output19, LOW);
} else if (header.indexOf("GET /21/on") >= 0) {
Serial.println("GPIO 21 on");
output21State = "on";
digitalWrite(output21, HIGH);
} else if (header.indexOf("GET /21/off") >= 0) {
Serial.println("GPIO 21 off");
output21State = "off";
digitalWrite(output21, LOW);
}

HTML section

Actually, this one is still in loop section, but I would like to differentiate it so it will be easier to be understood. I wouldn’t go into pretty detail for this one!

The following code is for styling the web page. Other than the GPIO that is used, I also modified this section from Rui Santos. But to be fair, my code is still pretty similar to it. But still, this is my own version and I’m pretty satisfied with it! TL;DR I made the dark mode of Rui Santos’s code with a different font type for the title. In short, what can we style from this code are the web page and the buttons appearances.

// CSS to style the on/off buttons 
// Feel free to change the background-color and font-size attributes to fit your preferences
client.println("<style>html { font-family: courier; display: inline-block; margin: 0px auto; text-align: center; color: white; background-color: black;}");
client.println(".button { background-color: #45E6A3; border: none; color: black; padding: 16px 40px;");
client.println("text-decoration: none; font-size: 30px; margin: 2px; cursor: pointer;}");
client.println(".button2 {background-color: #DEDEDE;}</style></head>");

To set the web page first heading, we use this line.

// Web Page Heading
client.println("<h1>ESP32 Web Server</h1>");

Next, to display the buttons and corresponding state for GPIO 19, we use the following code.

// Display current state, and ON/OFF buttons for GPIO 19  
client.println("<p>GPIO 19- State " + output19State + "</p>");
// If the output19State is off, it displays the ON button
if (output19State=="off") {
client.println("<p><a href=\"/19/on\"><button class=\"button\">ON</button></a></p>");
} else {
client.println("<p><a href=\"/19/off\"><button class=\"button button2\">OFF</button></a></p>");
}

We use the same procedures for GPIO 21.

Last but not least, when the response ends, we clear the header variable, and stop the connection with the client (browser) with client.stop()

// Clear the header variable
header = "";
// Close the connection
client.stop();

Final Thought

In conclusion, with the ESP32 web server, we can do many things like turning on/off LEDs by clicking the button on the web server. It seems that our story is already ended, I hope that my story can bring you guys more inspiration to learn more about technology, especially embedded systems. See you guys in the next story and don’t forget to keep learning! Have fun guys!

Sign up to discover human stories that deepen your understanding of the world.

No responses yet

What are your thoughts?