Lecture 5 - Web Servers and Clients
Outlines
- Goal: learn how to use the ESP32's Wi-Fi capabilities to create interactive, web-based IoT applications.
- Two projects we will build:
- ESP32 as a Web Server: create a local web page, hosted on the ESP32, to remotely control outputs and display live sensor data from a browser.
- ESP32 as a Web Client: send data from the ESP32 to a cloud IoT platform, allowing you to monitor sensors from anywhere in the world.
- Lecture Outline:
- Introduction to a Web Server
- Basic HTML and CSS
- ESP32 as a Local Web Server to Control Actuators
- ESP32 as a Local Web Server to Monitor Sensor Data
- ESP32 as a Client of Web Services
- Advanced Topics for ESP32 Web Servers and Clients
Analogy Think of this lecture like learning to run a small shop (the ESP32). First you learn how customers (clients) and shops (servers) talk to each other (HTTP), then you learn to decorate your shop window (HTML/CSS), then you actually open the shop for two kinds of business: taking orders from customers (control outputs) and displaying your stock levels (monitor sensors). Finally, you learn to be a customer yourself, ordering supplies from a big warehouse in the cloud (IoT platform).
References
- Random Nerd Tutorials: https://randomnerdtutorials.com/projects-esp32/
- Last Minute Engineers: https://lastminuteengineers.com/esp32-arduino-ide-tutorial/
- Thai Easy Elect (Thai Language): https://blog.thaieasyelec.com/espino32-article-table-of-contents/
1. Introduction to a Web Server
1.1 Client-Server Architectures
1. Request-response
- This is the fundamental communication pattern for the web.
- Diagram: Client ⇄ Server
- It's a simple, three-step process:
- Request: A client (like your web browser) sends a request message to a server.
- e.g.
"GET /homepage.html"
- e.g.
- Process: The server receives the request and processes it.
- Finds the requested file.
- Response: The server sends a response message back to the client.
- Sends the HTML code for the homepage.
- Request: A client (like your web browser) sends a request message to a server.
Analogy This is like ordering food at a restaurant counter: you (client) ask for a dish (request), the kitchen (server) prepares it (process), and the server brings your food back to you (response).
Ex: How Your Browser Gets a Web Page
When you type a URL and press Enter, a simple four-step process happens in the background:
- You Start: You type a URL into your web browser.
- The Request: Your browser (the Client) sends an HTTP Request to the web server.
- "Please give me the file for this web page."
- The Response: The Server finds the requested files (HTML, CSS, etc.) and sends an HTTP Response back to your browser.
- "Here are the files you asked for."
- The Result: Your browser receives the files and renders the web page on your screen.
2. Web Server
What is a Web Server?
- A program that continuously listens for incoming HTTP requests from clients (like a web browser).
- When a request is received, it processes it and sends back an HTTP response (like an HTML page).
1.2 HTTP Transmission Protocol
Related
1. Process
Standard procedure when opening a website (the computer we use to open a website is called a client; the computer that stores the HTML source code is called a server):
- The client sends an HTTP request message to the server.
- The server sends an HTTP response message (including an HTML page) to the client.
2. HTTP Request Message Format
The web server will receive the HTTP request message from the client. Its format is:
METHOD /path-to-resource HTTP/version-number
Header-Name-1: value
Header-Name-2: value
a blank line
[optional request body]
where:
- METHOD = a request method, e.g.,
getorpost.- The method "get" will be the method we use (similar to typing a URL).
- /path-to-resource = URL path after the host website name.
- Header-Name-1 =
Host; value = the host website name - Read more from: http://www.w3schools.com/Tags/ref_httpmethods.asp
Example: If you type www.example.com/index.html on your web browser and press Enter, your computer works as a client and sends the following HTTP request message to the server:
GET /index.html HTTP/1.1
Host: www.example.com
The HTTP request message itself that is sent out will be one line of text (to represent the above HTTP request message):
GET /index.html HTTP/1.1\r\nHost: www.example.com\r\n\r\n
\r = carriage return; \n = go to the new line.
3. HTTP Response Message
The server will send the HTTP response message to the client. The client's web browser will read this message and display the corresponding web page. The format is:
HTTP/version-number status-code message
Header-Name-1: value
Header-Name-2: value
A blank line
[HTML Body]
Examples of status-code and message:
200 OK400 Bad Request404 Not Found- Read more from: https://en.wikipedia.org/wiki/Hypertext_Transfer_Protocol
Example: If you type www.example.com/index.html on your web browser and press Enter, an example of the HTTP response message (sent back from the web server) is shown here. The web browser will display the web page corresponding to the HTML body.
HTTP/1.1 200 OK
Date: Mon, 23 May 2005 22:38:34 GMT
Content-Type: text/html; charset=UTF-8
Content-Encoding: UTF-8
Content-Length: 138
Last-Modified: Wed, 08 Jan 2003 23:11:55 GMT
Server: Apache/1.3.3.7 (Unix) (Red-Hat/Linux)
ETag: "3f80f-1b6-3e1cb03b"
Accept-Ranges: bytes
Connection: close
<html>
<head>
<title>An Example Page</title>
</head>
<body>
Hello World, this is a very simple HTML document.
</body>
</html>
Analogy An HTTP request/response is like a letter exchange: the request "envelope" has an address line (METHOD /path HTTP/version) and extra notes (headers), then a blank line before any enclosed letter (body). The response envelope similarly starts with a status line ("Everything's fine" = 200 OK, or "Couldn't find it" = 404) followed by headers and then the actual content (HTML body).
2. Basic HTML and CSS
In this section, we build a basic web page with step-by-step instructions, so that we can easily change how it looks. This section consists of:
- 2.1 Basic HTML
- 2.2 Basic CSS
2.1 Basic HTML
1. Introducing HTML
- HTML stands for Hyper Text Markup Language.
- It is the standard language used to structure the content of a web page.
- HTML uses tags (e.g.,
<p>,<h1>) to define different elements like paragraphs and headings. - A web browser's job is to read the HTML file and render the content visually based on these tags.
<!DOCTYPE html>
<html>
<head>
<title>My Web Page</title>
</head>
<body>
<h1>Hello, World! </h1>
<p>This is the content you can see. </p>
</body>
</html>- The first line of any HTML document is always
<!DOCTYPE html>. This tells the web browser this document is an HTML file. - The structure of the web page should go between the
<html>and</html>tags. The<html>tag indicates the beginning of a web page and the</html>tag indicates the end of the page. - The HTML document is divided into two main parts: the head and the body. The head goes within the
<head>and</head>tags and the body within the<body>and</body>tags. - The head is where you insert data about the HTML document that is not directly visible to the end user, but adds functionalities to the web page like the title, scripts, styles and more — this is called metadata.
- The body includes the content of the page like headings, text, buttons, tables, etc.
Analogy Think of an HTML file like a house blueprint:
<!DOCTYPE html> says "this is a house plan", <head> is like the utility/planning info that isn't seen by visitors (wiring diagrams, permits), and <body> is the actual rooms and furniture people walk through and see.
Ex: Create a HTML File
- Open a Text Editor program (you can use any text editor you like; we use Notepad) and write the HTML text below.
- Save the file as
index.html. - Open your browser and drag the HTML file to a browser tab.
- You will just see a blank page because you haven't added anything to the HTML file yet.
Ex: Create a Title
The title of your web page is the text that shows in the web browser tab.
- The web page title should go between the
<title>and</title>tags, that should go between the<head>and</head>tags. - Add a title to your web page by typing the title between
<title>and</title>tags, as shown below.
<!DOCTYPE html>
<html>
<head>
<title>ESP32 Web Server</title>
</head>
<body>
</body>
</html>Ex: Create a Heading
Headings are used to structure the text on the web page.
- Headings begin with an
hfollowed by a number that indicates the heading strength. - For example
<h1>and</h1>are the tags for heading 1,<h2>and</h2>for heading 2, until heading 6. - The heading tags should be between the
<body>and</body>tags.
<!DOCTYPE html>
<html>
<head>
<title>ESP32 Web Server</title>
</head>
<body>
<h1>ESP32 WebServer</h1>
</body>
</html>Ex: Create a Paragraph
The paragraphs are used to place text.
- Every paragraph should go between the
<p>and</p>tags. Add some paragraphs to show the state of GPIO 26 and GPIO 27.
<!DOCTYPE html>
<html>
<head>
<title>ESP32 Web Server</title>
</head>
<body>
<h1>ESP32 WebServer</h1>
<p>GPIO 26 - State</p>
<p>GPIO 27 - State</p>
</body>
</html>Ex: Create a Button
How to create a button: Use the <button> tag.
- The text between
<button>and</button>becomes the label on the button's face.
Example Code:
<p>GPIO 26: <button>ON</button> <button>OFF</button></p>
<p>GPIO 27: <button>ON</button> <button>OFF</button></p>- Note that when we click on the buttons, nothing happens because those buttons do not have any hyperlink associated with them. We need to add hyperlinks to the buttons.
<!DOCTYPE html>
<html>
<head>
<title>ESP32 Web Server</title>
</head>
<body>
<h1>ESP32 WebServer</h1>
<p>GPIO 26 - State</p>
<p><button>ON</button></p>
<p><button>OFF</button></p>
<p>GPIO 27 - State</p>
<p><button>ON</button></p>
<p><button>OFF</button></p>
</body>
</html>Ex: Create a Hyperlink
HTML links are called hyperlinks. You can add hyperlinks to text, images, buttons, or any other HTML element.
-
To add a hyperlink, use the
<a>and</a>tags, in the following format:<a href="url">element</a> -
Between the
<a>and</a>tags, place the HTML element you want to apply the link to. For example, to apply the link to one of the "OFF" buttons:<a href="url"><button>OFF</button></a> -
The
hrefattribute specifies where the link should go. When you click the GPIO 26 ON button, you want to be redirected to the root page followed by/26/on. To do that, add that URL to thehrefattribute:<a href="/26/on"><button>ON</button></a> -
When you click the GPIO 26 OFF button, you want to redirect to
/26/off:<a href="/26/off"><button>OFF</button></a>
You should add the appropriate hyperlink to each of your buttons as follows:
<!DOCTYPE html>
<html>
<head>
<title>ESP32 Web Server</title>
</head>
<body>
<h1>ESP32 WebServer</h1>
<p>GPIO 26 - State</p>
<p><a href="/26/on"><button>ON</button></a></p>
<p><a href="/26/off"><button>OFF</button></a></p>
<p>GPIO 27 - State</p>
<p><a href="/27/on"><button>ON</button></a></p>
<p><a href="/27/off"><button>OFF</button></a></p>
</body>
</html>- At the moment, you get the error "file was not found" because you do not have any file at that URL.
- Later, this will be solved on the Arduino IDE, because your ESP32 will send different HTML text when you click on the buttons.
Analogy A hyperlink
<a href="/26/on"> is like writing a return address on an order slip: clicking the button doesn't just look pretty — it tells the "shop" (server) exactly which department (/26/on) to route your order to.
2.2 Basic CSS
1. Syntax
- CSS stands for Cascading Style Sheets and it is used to describe how the elements in a web page look.
- It describes a certain part of the page like a particular tag or a particular set of tags.
- The CSS can be added to the HTML file or in a separate file that is referenced by the HTML file. We add the CSS to the HTML file because it is easier to add to the Arduino IDE.
- When added to the HTML file, the CSS should go between the
<style>and</style>tags, that should go in the head of the HTML file. - CSS uses selectors to style your HTML content. The selector points to the HTML element you want to style. Selectors have properties, which in turn have values.
- The style for a certain selector should go between curly brackets
{}. - The value is attributed to a property using a colon
:. - Every value should end with a semicolon
;. - Each selector can have, and normally does have, more than one property.
- The style for a certain selector should go between curly brackets
Analogy CSS syntax is like filling out a form:
selector { property: value; } reads as "For this [selector] element, set [property] to [value]." — same structure as "For this [room], set [paint color] to [blue]."
2. Styling the Page
If we want to set the html style which will be applied to the whole web page (i.e., all web page content between <html>and </html>), we design it using the html selector. For example, define the font-family to Helvetica, display the content as a block, set 0px for the margins, and align all the page at the center using "auto":
html {
font-family: Helvetica;
display: inline-block;
margin: 0px auto;
text-align: center;
}We add the html selector within the <style> tags:
<!DOCTYPE html>
<html>
<head>
<title>ESP32 Web Server</title>
<style>
html { font-family: Helvetica;
display: inline-block;
margin:0px auto;
text-align: center;
}
</style>
</head>
<body>
<h1>ESP32 WebServer</h1>
<p>GPIO 26 - State</p>
<p><a href="/26/on"><button>ON</button></a></p>
<p><a href="/26/off"><button>OFF</button></a></p>
<p>GPIO 27 - State</p>
<p><a href="/27/on"><button>ON</button></a></p>
<p><a href="/27/off"><button>OFF</button></a></p>
</body>
</html>3. Styling the Button
Next, we style the buttons that we use.
-
We create a class attribute for a button. The syntax of a class attribute is:
<element class="classname">Here, the element is
button. The classname for ON will be namedbuttonwhile the classname for OFF will bebuttonandbutton2:<p><a href="/26/on"><button class="button">ON</button></a></p> <p><a href="/26/off"><button class="button button2">OFF</button></a></p>The buttons for GPIO27 will be designed the same way.
There is nothing changed since we did not yet define the style of the class names
buttonandbutton2. -
To specify the style of the classname
button, we add the following intoindex.html:.button { background-color: #4CAF50; border: none; color: white; padding: 16px 40px; text-decoration: none; font-size: 30px; margin: 2px; cursor: pointer; }- The
background-colorproperty, as the name suggests, defines the button's background color. Colors can be set using their name — HTML recognizes basic color names — or by using the hexadecimal or RGB color code (search "hexadecimal color picker" online for a reference). Here we're using hexadecimal color code. - We set the
borderproperty tonone, and the button text towhite. - The
paddingdefines a space around the button — in this case 16px by 40px. - We set the text decoration to
none, font size of30px, margin of2px, and the cursor topointer— this changes the cursor to a pointer when you drag the mouse over the button.
- The
-
To specify the style of the classname
button2, we add:.button2 { background-color: #555555 }Here, we only define the color (grey) for the classname
button2. The OFF button belongs to classname "button" and classname "button2", so it will have properties from both.
We add these two CSS styles for the button elements within the <style> tags in index.html and refresh the webpage.
Analogy A CSS
class is like a uniform: giving both the ON and OFF buttons the button class means they both wear the same base uniform (green, padded, pointer cursor). Adding button2 on top of OFF is like adding an extra grey jacket over that uniform — it inherits everything from button plus its own tweaks.
4. Metadata
In the head of the index.html file, under the <title> tag, we add two lines:
-
Add the
<meta>tag that makes your web page responsive in any web browser (including mobile web browser):<meta name="viewport" content="width=device-width, initial-scale=1">The
<meta>tag provides metadata about the HTML document. Metadata will not be displayed on the page, but provides useful information to the browser such as how to display the content. -
Add the following line:
<link rel="icon" href="data:,">To prevent requests from the browser to the ESP32 about the favicon. The favicon is the shortcut icon that appears on the web browser tab.
Complete index.html file (so far):
<!DOCTYPE html>
<html>
<head>
<title>ESP32 Web Server</title>
<meta name="viewport" content="width=device-width, initialscale=1">
<link rel="icon" href="data:,">
<style>
html { font-family: Helvetica;
display: inline-block;
margin:0px auto;
text-align: center;
}
.button { background-color: #4CAF50;
border: none;
color: white;
padding: 16px 40px;
text-decoration: none;
font-size: 30px;
margin: 2px;
cursor: pointer;
}
.button2 { background-color: #555555;
}
</style>
</head>3. ESP32 as a Local Web Server to Control Actuators
In this section, we learn how to create a simple web server with the ESP32 to control outputs. The web server can be accessed with any device that has a browser: smartphone, tablet, laptop, on the local network. This section consists of:
- 3.1 Building ESP32 as a Local Web Server
- 3.2 ESP32 Web Server to Control Outputs
- 3.3 Code Explanation
3.1 Building ESP32 as a Local Web Server
1. Web Server
How the ESP32 uses this:
- We can run a web server directly on the ESP32.
- This allows the ESP32 to "host" a web page that you can access from your phone or computer to control outputs or view sensor data.
2. ESP32 as a Web Server
Practical example with an IoT device called ESP32 that acts as a web server in the local network.
- The Local Network:
- The ESP32 connects to your Wi-Fi router.
- Your computer or smartphone connects to the same router/access point.
- As a result, all devices are on the same local network.
- The Interaction:
- You type the ESP32's unique IP address into your browser on a client computer.
- Your browser sends an HTTP Request directly to the ESP32.
- The ESP32 processes the request and sends back an HTTP Response.
- As a result, your browser displays the web page, sensor data, or controls sent by the ESP32.
Analogy The ESP32 becomes like a tiny shopkeeper who has a stall inside the "mall" of your home Wi-Fi network. Anyone in the same mall (same Wi-Fi) can walk up to the stall's address (IP address) and place an order, without needing the internet at all.
3.2 ESP32 Web Server to Control Outputs
1. Project Outline
Project Goal: To build a web server on the ESP32 that hosts a web page with buttons to control two LEDs.
How It Works:
- Connect: The ESP32 (server) and your computer/phone (client) must be on the same Wi-Fi network.
- Access: Open a web browser on your computer/phone and type in the ESP32's IP address.
- Control: Click the buttons on the web page to instantly turn the LEDs (connected to GPIOs 26 & 27) ON or OFF.
Beyond this Example: This is a foundational project. The LEDs can easily be replaced by relays, motors, or any other actuator you want to control remotely.
Step-by-step interaction (Client ⇄ ESP32, LEDs on GPIO 26 & 27, each with a 330Ω resistor to GND):
- Step 1: On a browser (at Client), the user enters the IP address of the ESP32.
- HTTP Request:
GET / HTTP/1.1,Host: 192.168.43.164 - HTTP Response:
HTTP/1.1 200 OK+ HTML Code
- HTTP Request:
- Step 2: If the user presses the ON button of LED1 (pin 26), LED1 turns on. The web page is revised: LED1 state = On, and its button becomes OFF.
- HTTP Request:
GET /26/on HTTP/1.1
- HTTP Request:
- Step 3: If the user presses the OFF button of LED1, LED1 turns off. The web page is revised: LED1 state = Off, and its button becomes ON.
- HTTP Request:
GET /26/off HTTP/1.1
- HTTP Request:
- Step 4: If the user presses the ON button of LED2 (pin 27), LED2 turns on; button becomes OFF.
- HTTP Request:
GET /27/on HTTP/1.1
- HTTP Request:
- Step 5: If the user presses the OFF button of LED2, LED2 turns off; button becomes ON.
- HTTP Request:
GET /27/off HTTP/1.1
- HTTP Request:
Analogy Each button press is like mailing a very short postcard with only an address on it (
GET /26/on). The ESP32 "postmaster" reads the address, does the requested action (flips a light switch), and mails back a postcard confirming the new state of the page.
2. Web Page Design
The HTML code is similar to what we designed previously.
- Case: The LED is OFF and the ON button is active.
- Case: The LED is ON and the OFF button is active.
3. Schematic
Connect two LEDs to ESP32:
- LED1: GPIO 26 → long leg (anode) → LED → short leg → 330Ω resistor → GND
- LED2: GPIO 27 → long leg (anode) → LED → short leg → 330Ω resistor → GND
- Both resistors connect back to the Pin GND of ESP32.
4. Arduino Code
The Arduino code WebServer_ControlOutputs.ino will ask the ESP32 to send an HTTP response message when it receives the HTTP request from a client (web browser). Inside this message is the HTML body written previously.
Steps:
-
Write this code in your Arduino IDE.
-
Fill in your SSID and Password of your access point:
// Replace with your network credentialsconst char* ssid = "Your SSID";const char* password = "Your Password"; -
Upload the code to your ESP32.
Full Arduino code:
// Load Wi-Fi library
#include <WiFi.h>
// Replace with your network credentials
const char* ssid = "Your SSID";
const char* password = "Your Password";
// 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 output26State = "off";
String output27State = "off";
// Assign output variables to GPIO pins
const int output26 = 26;
const int output27 = 27;
// 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(output26, OUTPUT);
pinMode(output27, OUTPUT);
// Set outputs to LOW
digitalWrite(output26, LOW);
digitalWrite(output27, LOW);
// Connect to Wi-Fi network with SSID and password
Serial.print("Connecting to ");
Serial.println(ssid);
WiFi.mode(WIFI_STA);
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 /26/on") >= 0) {
Serial.println("GPIO 26 on");
output26State = "on";
digitalWrite(output26, HIGH);
} else if (header.indexOf("GET /26/off") >= 0) {
Serial.println("GPIO 26 off");
output26State = "off";
digitalWrite(output26, LOW);
} else if (header.indexOf("GET /27/on") >= 0) {
Serial.println("GPIO 27 on");
output27State = "on";
digitalWrite(output27, HIGH);
} else if (header.indexOf("GET /27/off") >= 0) {
Serial.println("GPIO 27 off");
output27State = "off";
digitalWrite(output27, 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: Helvetica; display: inline-block; margin: 0px auto; text-align: center;}");
client.println(".button { background-color: #4CAF50; border: none; color: white; padding: 16px 40px;");
client.println("text-decoration: none; font-size: 30px; margin: 2px; cursor: pointer;}");
client.println(".button2 {background-color: #555555;}</style></head>");
// Web Page Heading
client.println("<body><h1>ESP32 Web Server</h1>");
// Display current state, and ON/OFF buttons for GPIO 26
client.println("<p>GPIO 26 - State " + output26State + "</p>");
// If the output26State is off, it displays the ON button
if (output26State=="off") {
client.println("<p><a href=\"/26/on\"><button class=\"button\">ON</button></a></p>");
} else {
client.println("<p><a href=\"/26/off\"><button class=\"button button2\">OFF</button></a></p>");
}
// Display current state, and ON/OFF buttons for GPIO 27
client.println("<p>GPIO 27 - State " + output27State + "</p>");
// If the output27State is off, it displays the ON button
if (output27State=="off") {
client.println("<p><a href=\"/27/on\"><button class=\"button\">ON</button></a></p>");
} else {
client.println("<p><a href=\"/27/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("");
}
}5. Demonstration
- When finishing uploading the code to ESP32, the serial monitor will show the IP address of ESP32 which is now working as a web server.
- Connect your computer/phone to the same access point (that ESP32 is connecting to). On a web browser, type the IP address (of ESP32) on the URL and press Enter. You will see the web page — clicking the buttons will turn the LEDs on/off.
3.3 Code Explanation
Mainly the code consists of the following parts:
-
Set ESP32 as a webserver:
// Set web server port number to 80WiFiServer server(80); -
Connect to the access point:
WiFi.mode(WIFI_STA);WiFi.begin(ssid, password);while (WiFi.status() != WL_CONNECTED) { -
Listen to a client and receive the HTTP request (stored in the variable named
header).Note
- At first, when the user enters the IP address of ESP32 in the client's browser, the client will send an HTTP request:
"GET / HTTP1.1"to the ESP32. - Later, after the client receives the HTTP response including the HTML source code, the browser will display the webpage.
- If we click the ON button of pin 26, the text "GET /26/on" appears in the HTTP request; turns the LED at pin 26 on.
- If we click the OFF button of pin 26, the text "GET /26/off" appears; turns the LED at pin 26 off.
- Similarly for pin 27 with "GET /27/on" and "GET /27/off".
- At first, when the user enters the IP address of ESP32 in the client's browser, the client will send an HTTP request:
-
Check whether the HTTP request stores "GET /26/on", "GET /26/off", "GET /27/on", or "GET /27/off". Then turn on/off the LED correspondingly.
- The
.indexOf()function checks whether we have the specified text in the specified string variable. - The
header.indexOf("GET /26/on")command will return:>= 0if there is "GET /26/on" in theheadervariable.-1if there is no "GET /26/on" in theheadervariable.
- Here, the
headervariable stores the HTTP request message.
- The
-
Send the HTTP response message (including the HTML body) to the client (Line 99-133).
- The variable name
clientis used to represent the current client that is connecting to ESP32. It has been defined in Line 56. - The
client.println()function sends the message inside the""to the client. A series of texts sent byclient.println()is the HTTP response message.
- The variable name
Analogy
header.indexOf("GET /26/on") is like scanning a mail envelope's text with a highlighter for a specific keyword. If found, you get its position (≥0, "found it, page such-and-such"); if not, you get -1("not in this letter at all").
4. ESP32 as a Local Web Server to Monitor Sensor Data
This section consists of:
- 4.1 ESP32 Web Server to Monitor Sensor Data
- 4.2 Code Explanation
4.1 ESP32 Web Server to Monitor Sensor Data
1. Project Outline
Project Goal: To build a web server on the ESP32 that displays readings from a potentiometer (connected to pin A0).
How It Works:
- Connect: The ESP32 (server) and your computer/phone (client) must be on the same Wi-Fi network.
- Access: Open a web browser and type in the ESP32's IP address.
- Monitor: The web page will display the real-time value from the potentiometer.
Beyond this Example: This project is a template for monitoring any sensor. You can easily add more sensors (temperature, humidity, etc.) and display all their data on one dashboard.
Interaction (Potentiometer wired between Pin 3v3 of ESP32 and GND, wiper to pin A0):
- Step 1: On a browser (at Client), the user enters the IP address of the ESP32.
- HTTP Request:
GET / HTTP/1.1 - HTTP Response:
HTTP/1.1 200 OK+ HTML Code
- HTTP Request:
- Step 2: The user rotates the knob of the potentiometer to change its value. Thereafter, the user presses the refresh button on the browser. The web page updates the potentiometer value.
2. Web Page Design
In this project, we display the sensor data in a table in a web page. The HTML code is similar to the previous one except we create a table consisting of two steps. (More details: https://www.w3schools.com/html/html_tables.asp)
- In the
<style>tags, define the style of the table — set the table border width to 1 pixel and locate the table at the center of the page:
table, th, td {
border: 1px solid black;
margin-left:auto;
margin-right:auto;
}- In the
<body>tags, create a table using the following tags:- The
<table>tag defines an HTML table. - The
<th>tag defines the table header. By default, the text in<th>elements is bold and centered. - The
<tr>tag defines a row. - The
<td>tag defines a cell in a row. By default, the text in<td>elements is regular and left-aligned.
- The
<body>
<h1>ESP32 WebServer</h1>
<table>
<tr>
<th>Sensor</th><th>Value</th>
</tr>
<tr>
<td>Potentiometer</td><td>500</td>
</tr>
</table>
</body>
</html>Complete HTML code:
<!DOCTYPE html>
<html>
<head>
<title>ESP32 Web Server</title>
<meta name="viewport" content="width=device-width, initialscale=1">
<link rel="icon" href="data:,">
<style>
html { font-family: Helvetica;
display: inline-block;
margin:0px auto;
text-align: center;
}
table, th, td {
border: 1px solid black;
margin-left:auto;
margin-right:auto;
}
</style>
</head>
<body>
<h1>ESP32 WebServer</h1>
<table>
<tr>
<th>Sensor</th><th>Value</th>
</tr>
<tr>
<td>Potentiometer</td><td>500</td>
</tr>
</table>
</body>
</html>3. Schematic
Connect a potentiometer to pin A0 of ESP32: Pin 3v3 of ESP32 → Potentiometer → A0 (wiper) → and the other end to Pin GND of ESP32.
4. Arduino Code
The Arduino code WebServer_MonitorSensor.ino asks the ESP32 to send an HTTP response message when it receives an HTTP request from a client. Inside this message is the HTML body (including the potentiometer value) written previously.
Steps:
- Write this code in your Arduino IDE.
- Fill in your SSID and Password of your access point.
- Upload the code to your ESP32.
Full Arduino code:
// Load Wi-Fi library
#include <WiFi.h>
// Replace with your network credentials
const char* ssid = "MyWiFi";
const char* password = "Moon15Star18";
// Set web server port number to 80
WiFiServer server(80);
// Variable to store the HTTP request
String header;
// 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);
// Connect to Wi-Fi network with SSID and password
Serial.print("Connecting to ");
Serial.println(ssid);
WiFi.mode(WIFI_STA);
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();
// 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: Helvetica; display: inline-block; margin: 0px auto; text-align: center;}");
client.println("table, th, td { border: 1px solid black; margin-left:auto; margin-right:auto;}");
client.println("</style></head>");
// Web Page Heading
client.println("<body><h1>ESP32 Web Server</h1>");
// Create a table
client.println("<table>");
client.println("<tr><th>Sensor</th><th>Value</th></tr>"); // First row
client.print("<tr><td>Potentiometer</td><td>"); // Second row
client.print(analogRead(A0)); // Read the potentiometer value
client.println("</td></tr>"); // Second row
client.println("</table>");
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("");
}
}5. Demonstration
- When finishing uploading the code to ESP32, the serial monitor will show the IP address of ESP32 which is now working as a web server.
- Connect your computer/phone to the same access point. On a web browser, type the IP address of ESP32 on the URL and press Enter. You will see the web page showing the potentiometer value. To update the value, you must press the refresh button.
4.2 Code Explanation
The Arduino code of this project is quite similar to the previous one. The main difference is in the HTML body where we send the potentiometer value (read from pin A0) along with the HTML code (Line 82):
client.print(analogRead(A0));Analogy
analogRead(A0) is like glancing at a dial/gauge and jotting its current reading directly into a report — every time someone refreshes the page, the ESP32 peeks at the potentiometer again and writes the fresh number into the HTML "report" it sends back.
5. ESP32 as a Client to an IoT Cloud Platform
This section consists of:
- 5.1 IoT Cloud Platform
- 5.2 Showing Sensor Data on ThingSpeak
- 5.3 Code Explanation
5.1 IoT Cloud Platforms: Connecting to the World
Related
- What are they?
- Specialized web services designed to ingest, store, visualize, and manage data from IoT devices.
- Why use one?
- It is the easiest way to monitor and control your devices securely over the internet, from anywhere in the world.
- How do we connect?
- The ESP32 acts as a client.
- It sends data to the platform's API (Application Programming Interface), which is like a special, secure mailbox for your data.
- Popular Platforms: ThingSpeak, Ubidots, Netpie (Nectec), Google, IBM Watson, AWS, Cisco, Kaa, Oracle, Thingworx, etc.
Analogy If the earlier local web server was a small in-house stall, an IoT cloud platform is like shipping your goods to a big central warehouse (accessible from anywhere) instead of only letting people visit your local stall in person.
5.2 Sending ESP32 Data to the ThingSpeak Cloud
1. Project Outline
Project Goal: To send sensor data from an ESP32 to the ThingSpeak cloud platform for remote monitoring from anywhere.
Architecture:
- Client: ESP32 (reading a potentiometer on pin A0)
- Server: ThingSpeak IoT Cloud Platform
Process (repeats every 10 seconds):
- Read: The ESP32 reads the current value from the potentiometer and a random number.
- Send: The ESP32 sends two values every 10 seconds via an HTTP Request to your unique ThingSpeak channel API.
- Visualize: ThingSpeak receives these two values, stores them, and automatically plots them on two charts.
Result: A cloud-hosted dashboard that you can access from any browser to monitor your sensor data in real-time.
Interaction Diagram:
- ESP32 (A Web Client) → sends HTTP request (potentiometer and a random number) → ThingSpeak Server
- ThingSpeak Server → sends back an HTTP response → ESP32
- User using a Web Browser (A Web Client) → sends HTTP request → ThingSpeak Server
- ThingSpeak Server → sends back HTTP response including the HTML code → User's browser
The key in this project:
- ESP32 sends the HTTP Get message to ThingSpeak. This message includes the potentiometer value and a random number.
- The HTTP Get message is in this format (it is a string):
https://api.thingspeak.com/update?api_key=YourAPIkey&field1=250&field2=40
where YourAPIkey is your ThingSpeak API key, 250 is your potentiometer value, and 40 is your random number.
Analogy This URL is like a filled-out order form mailed to the warehouse: the address is
api.thingspeak.com/update, and the form fields are api_key (your account ID), field1 (potentiometer reading), and field2 (random number) — ThingSpeak reads the form and files the numbers into your channel's charts.
2. Sign up ThingSpeak and Create a Channel
ThingSpeak has a free API that allows you to store and retrieve data using HTTP. Steps to create a ThingSpeak channel:
- Create a ThingSpeak account.
- Create a new channel by clicking on the New Channel button.
- In your new channel, fill in:
- Name:
Sensor Data - Field 1:
Potentiometer - Field 2:
Random Number - The other fields are blank. We fill in Field 1 and Field 2 since we will show two sensor data. Make sure the boxes after Field 1 and Field 2 are checked.
- Name:
- Click the Save button at the bottom of the page.
- Go to your ThingSpeak channel ("Sensor Data"). There are many tabs. Clicking the Private View tab shows the Field 1 chart and Field 2 chart, which display the data sent from the ESP32.
- Click on the API Keys tab to see your Write API key. Record it since we will use it in the Arduino code.
3. Schematic
Connect a potentiometer to pin A0 of ESP32: Pin 3v3 of ESP32 → Potentiometer → A0 (wiper) → and the other end to Pin GND of ESP32.
4. Arduino Code
The Arduino code WebClient_ThingSpeak.ino asks the ESP32 to send two values (potentiometer value and a random number) to ThingSpeak.
Steps:
-
Write this code in your Arduino IDE.
-
Fill in your SSID and Password of your access point:
// Replace with your network credentialsconst char* ssid = "Your SSID";const char* password = "Your Password"; -
Put your Write API Key from ThingSpeak:
// REPLACE WITH THINGSPEAK.COM API KEYString serverName = "http://api.thingspeak.com/update?api_key=YourWriteAPIkey"; -
Upload the code to ESP32.
Full Arduino code:
#include <WiFi.h>
#include <HTTPClient.h>
// Replace with your network credentials
const char* ssid = "MyWiFi";
const char* password = "Moon15Star18";
// REPLACE WITH THINGSPEAK.COM API KEY
String serverName = "http://api.thingspeak.com/update?api_key=LGUP3GH9R3ODSVNN";
// EXAMPLE:
//String serverName = "http://api.thingspeak.com/update?api_key=7HQJM49R8JAPR";
// THE DEFAULT TIMER IS SET TO 10 SECONDS FOR TESTING PURPOSES
// For a final application, check the API call limits per hour/minute to avoid getting blocked/banned
unsigned long lastTime = 0;
// Set timer to 10 seconds (10000)
unsigned long timerDelay = 10000;
void setup() {
Serial.begin(115200);
WiFi.begin(ssid, password);
Serial.println("Connecting");
while(WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.print("Connected to WiFi network with IP Address: ");
Serial.println(WiFi.localIP());
Serial.println("Timer set to 10 seconds (timerDelay variable), it will take 10 seconds before publishing the");
}
void loop() {
// Send an HTTP GET request
if ((millis() - lastTime) > timerDelay) {
// Check WiFi connection status
if(WiFi.status()== WL_CONNECTED){
WiFiClient client;
HTTPClient http;
String HttpRequest = serverName + "&field1=" + String(analogRead(A0)) + "&field2=" + String(random(100));
// Create the HTTP Get request to ThingSpeak
Serial.print("HTTP Request: ");
Serial.println(HttpRequest);
http.begin(client, HttpRequest);
//Another option --> http.begin(client, HttpRequest.c_str());
// Send HTTP GET request
int httpResponseCode = http.GET();
if (httpResponseCode>0) {
Serial.print("HTTP Response code: ");
Serial.println(httpResponseCode);
}
else {
Serial.print("Error code: ");
Serial.println(httpResponseCode);
}
// Free resources
http.end();
}
else {
Serial.println("WiFi Disconnected");
}
lastTime = millis();
}
}5. Demonstration
- When finishing uploading the code to ESP32, the ESP32 will try to connect to the WiFi access point.
- ESP32 sends the HTTP request message to ThingSpeak every 10 seconds.
- ThingSpeak receives the message, sends an HTTP response back, and updates the charts.
5.3 Code Explanation
Mainly the code consists of the following parts:
-
Specify your ThingSpeak API key:
// REPLACE WITH THINGSPEAK.COM API KEYString serverName = "http://api.thingspeak.com/update?api_key=LGUP3GH9R3ODSVNN"; -
Set ESP32 as a WiFi client and a HTTP client (to be able to send an HTTP Get request):
WiFiClient client;HTTPClient http; -
Create an HTTP request message:
String HttpRequest = serverName + "&field1=" + String(analogRead(A0)) + "&field2=" + String(random(100)); -
Call the
beginmethod on thehttpobject to store this URL on thehttpobject:http.begin(client, HttpRequest); -
Send the HTTP request by the GET method:
int httpResponseCode = http.GET();where
httpResponseCodestores the returned code from ThingSpeak.
\boxed{\text{HttpRequest} = \text{serverName} + \text{"&field1="} + \text{analogRead(A0)} + \text{"&field2="} + \text{random(100)}}
Analogy Building the
HttpRequest string is like taping extra sticky notes onto a base envelope (serverName) — one note says "field1 = [potentiometer reading]" and another says "field2 = [random number]" — before dropping the whole thing in the mailbox with http.GET().
6. Advanced Topics for ESP32 Web Servers and Clients
Advanced Topics for ESP32 Web Servers
The following topics could be useful for your work in the future:
- You might create a password to log into the ESP32 web server: https://randomnerdtutorials.com/esp32-esp8266-web-server-http-authentication/
- You might consider the web socket approach to automatically update the data on your web page: https://randomnerdtutorials.com/esp32-websocket-server-arduino/
- You might consider the asynchronous web server approach such that no information is shown in the URL of the web browser (which is not secure): https://randomnerdtutorials.com/esp32-async-web-server-espasyncwebserver-library/
- You might implement your ESP32 web to access from anywhere (globally): https://microcontrollerslab.com/accessing-esp32-web-server-anywhere-world-esp8266/
Advanced Topics for ESP32 Web Clients
The following topics could be useful for your work in the future:
- You might find more examples to use the HTTP GET method: https://randomnerdtutorials.com/esp32-http-get-open-weather-map-thingspeak-arduino/
- You might find more examples to use the HTTP POST method: https://randomnerdtutorials.com/esp32-http-post-ifttt-thingspeak-arduino/
- You might set ESP32 to send an email: https://randomnerdtutorials.com/esp32-send-email-smtp-server-arduino-ide/
- You might send your data to other IoT cloud platforms such as Google, AWS, etc.
Questions?
Linked from
- Chapter 1 - Introduction to Cloud Computing
- Chapter 12 - Internet Security Protocols and Standards
- Chapter 10 - System Architecture
- Chapter 7 - Development Strategies
- Lab 9 - Application-Layer Protocols
- Lecture 2 - IoT Architectures & a Use Case
- Lecture 3 - Introduction to ESP32
- Lecture 6 - MQTT Clients
- Lecture 4
- Lecture 3 - Data and Data Management II