esp32, esp32 wifi, esp32 web server, esp32 webserver, webserver esp32, web server esp32, esp32 server modeHello readers, I hope you all are doing great. It’s our second tutorial on the ESP32 Programming series and today, we will have a look at How to Create a Web Server with ESP32. In our previous tutorial, we introduced you to the basics of the ESP32 microcontroller. where we discuss How to set up Arduino IDE to program ESP32. In this tutorial, we will discuss creating a web server using the ESP32 module. One of the most interesting features of the ESP microcontroller series is its wireless connectivity via WiFi & Bluetooth.

Wireless connectivity protocols supported by ESP32 are:

  • Wi-fi : 802.11b/g/n/e/i
  • Bluetooth : BLE(Bluetooth low energy) and V4.2

ESP32 Wi-Fi

TCP/IP, entire 802.11 b/g/n/e/i WLAN MAC protocol, and Wi-Fi Direct specification are all implemented on the ESP32. When used in station(client) mode, the ESP 32 can communicate with the vast majority of Wi-Fi routers. It can also construct an access point that supports complete 802.11 b/g/n/e/I.

Wi-Fi Direct is also supported by the ESP32. Without the use of an access point, Wi-Fi Direct is an excellent alternative for peer-to-peer connections. Wi-Fi Direct is easier to set up and has substantially faster data transfer speeds than Bluetooth. This could be used to set up ESP32-based projects using a phone or tablet with Wi-Fi direct capability.

What is a Web server?

A web server is a piece of computer software and hardware that takes requests and responds to them using HTTP or HTTPS, the network protocols for distributing online content to client user agents.

esp32, esp32 wifi, esp32 web server, esp32 webserver, webserver esp32, web server esp32, esp32 server mode

Web Server & Client Communication

This is the fundamental concept of internet-based server and client communication. How can we establish a connection between the client and the Web server now? HTTP stands for hypertext transfer control and is a protocol for transferring data between a web client and a web server. In this tutorial, the webserver will be the ESP32, and the web client will be any web browser or Android app. A web client sends an HTTP GET request to the web server whenever it needs to view any web files.

ESP32 WebServer

The ESP32 Standalone Web Server is mobile responsive and can be accessed by any device that has a browser on a  local network like mobile phones, computers, laptops and tablets. But all the devices should be connected to the same Wi-Fi network as the ESP32 is connected to.

esp32, esp32 wifi, esp32 web server, esp32 webserver, webserver esp32, web server esp32, esp32 server mode

 

How ESP32 WebServer works with hardware?

  • For the demonstration purpose, we will create a webpage and will launch it through our ESP32 module, so ESP32 will be acting as a web server, serving the page.
  • This webpage will have 3 Buttons on it, which will be controlling three LEDs, we will turn ON or OFF respective LEDs using these buttons.
  • WebServer Page is shown in the below figure:

esp32, esp32 wifi, esp32 web server, esp32 webserver, webserver esp32, web server esp32, esp32 server mode

  • Now the question arises, how will ESP32 understand which Button has been pressed?
  • For that, we have created multiple links i.e. the HomePage Url will look like:

http://192.168.43.188/

  • When a user will click on LED 26 ON Button, we will redirect the user to:

http://192.168.43.188/26/on

  • Now, when the client wants to turn OFF the LED, we will redirect to:

http://192.168.43.188/26/off

  • So, actually, we are checking the request from the client and based on that request we are turning ON or OFF the respective LED.
  • Moreover, we are providing the same webpage to all the links but with the change in the state of each button i.e. if it’s ON then Blue, otherwise Green.

If it looks too complicated, don’t worry. These things will get more clear when we will cover the Arduino coding.

Note:

ESP32 server Modes:

ESP32 Wi-Fi module includes a number of useful characteristics, including the ability to use a soft access point mode, a station mode, or both modes at the same time. Only station mode will be discussed in this session. I’ll also cover how to use this board in soft access mode in future tutorials.

esp32, esp32 wifi, esp32 web server, esp32 webserver, webserver esp32, web server esp32, esp32 server mode

  1. Station Mode: The ESP32 board connects to your Wi-Fi network via a router in Station mode. The router serves as the communication channel between the web client and the ESP32. The IP address is obtained from the Wi-Fi router. Web clients can connect to the Web server using this IP address across a local network.
  2. Access Point Mode: In this mode, the ESP32 creates its own wireless Wi-Fi network, similar to the one provided by your existing router. We don’t need to connect the ESP2 to a Wi-Fi network in this mode. This Wi-Fi board can link up to 5 devices to the Wifi network it creates.

Controlling peripherals Using ESP32 Web Server

Connect the peripherals to the ESP32 board which you want to control through the ESP32 Web Server.

Here, we are going to control two external LEDs connected to LED1 (GPIO 26), LED2 (GPIO 27), and an inbuilt LED.

The following are the requirements for creating an ESP32 webserver to control peripherals:

  • ESP32 module
  • Internet connection
  • LEDs
  • Resistors
  • Connecting Wires

esp32, esp32 wifi, esp32 web server, esp32 webserver, webserver esp32, web server esp32, esp32 server mode

Arduino IDE Code

  • Using the Arduino IDE, upload the following code to the ESP32 module:

#include <WiFi.h>

// Replace with your network credentials
char* ssid = “ESP32”; //enter SSID
char* passphrase = “asdfgf@123”; // enter the 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”;
String builtin_led_state = “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);
pinMode(LED_BUILTIN, OUTPUT);

// Set outputs to LOW
digitalWrite(output26, LOW);
digitalWrite(output27, LOW);
digitalWrite(LED_BUILTIN, LOW);
// Connect to Wi-Fi network with SSID and password
Serial.print(“Connecting to “);
Serial.println(ssid);
WiFi.begin(ssid, passphrase);
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);
}
else if (header.indexOf(“GET /LED_BUILTIN/on”) >= 0)
{
Serial.println(“BUILTIN LED on”);
builtin_led_state = “on”;
digitalWrite(LED_BUILTIN, HIGH);
}
else if (header.indexOf(“GET /LED_BUILTIN/off”) >= 0)
{
Serial.println(“BUILTIN_LED off”);
builtin_led_state = “off”;
digitalWrite(LED_BUILTIN, 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: #3498db; border: none; grey: white; padding: 16px 40px;”);
client.println(“text-decoration: none; font-size: 30px; margin: 2px; cursor: pointer;}”);
client.println(“.button2 {background-color: #4CAF50;}</style></head>”);

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

// Display current state, and ON/OFF buttons for builtin led
client.println(“<p>LED_BUILTIN – State ” + builtin_led_state + “</p>”);
// If the LED is off, it displays the ON button
if (builtin_led_state==”off”)
{
client.println(“<p><a href=\”/LED_BUILTIN/on\”><button class=\”button\”>ON</button></a></p>”);
}
else
{
client.println(“<p><a href=\”/LED_BUILTIN/off\”><button class=\”button button2\”>OFF</button></a></p>”);
}

// Display current state, and ON/OFF buttons for GPIO 26
client.println(“<p>LED_1 – 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>LED_2 – 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(“”);
}
}

Note:

  • You need to modify the SSID and password with your network credentials.

Code Description:

Here, we’ll take a closer look at the code to see how it works.

  • The first task is to add a Wi-Fi library.
  • As mentioned previously, you must type your SSID and password inside the double quotes in the following lines.

esp32, esp32 wifi, esp32 web server, esp32 webserver, webserver esp32, web server esp32, esp32 server mode

  • As we are creating a web server, so we need to assign a port to it and normally we use port 80 for a local webserver.
  • So, in the below code, Port 80 is assigned to the webserver and then initialized a few variables:

esp32, esp32 wifi, esp32 web server, esp32 webserver, webserver esp32, web server esp32, esp32 server mode

  1. String header: variable to store the header of the HTTP request.
  2. Below the header variable, we have variables to store the current state of connected peripheral LEDs and built-in LED. If you wish to add more peripherals and save their states, you need to create more variables. By default, all LEDs are in the OFF state.
  3. Next, assigned GPIOs to each peripheral device or component. Here we are using GPIO 26(LED1) and GPIO 27(LED2). You can use any other suitable GPIOs.
  4. Lastly, we have initialized a few variables to check the connection timeout, we will check their working soon.

Arduino Setup() Function

  • Now let’s first have a look at the Arduino setup loop.
  • First, we have initialized our Serial Port at a baud rate of 115200, so that we could monitor the results at the serial terminal.

esp32, esp32 wifi, esp32 web server, esp32 webserver, webserver esp32, web server esp32, esp32 server mode

  • Define the GPIOs as OUTPUTs and set them to LOW, as by default LEDs will be off.
  • To set up a wifi connection, we called the WiFI.begin() and here we have provided our SSID and passphrase as variables.
  • Now our ESP32 will try to connect to the provided WiFi connection.
  • As you can see, we have a while loop, where we are checking the WiFi Status.
  • If ESP32 gets connected with WiFi, the while loop will break and a message will get printed on the Serial Monitor “WiFi Connected”.
  • Now our ESP32 is connected to the WiFi, so the router must have assigned an IP address to ESP32 and we are printing it on Serial using WiFi local IP Function.
  • Finally, we begin our server, to which we have assigned Port 80 at the start.

Arduino Loop() Function

Now, we are done with all the basic settings in the setup function. Let’s have a look at the code in the Loop function:

  • At the last line of the Setup function, we have started our webserver, so now ESP32 is acting as a webserver and is waiting for incoming clients.
  • But what will happen, when someone will hit the IP Address of this webserver?
  • So, in the loop function, first of all, we are listening to the incoming client using the server.available() function.
  • If any client is available i.e. someone has entered our IP Address in the browser then we will print the HTML page.

esp32, esp32 wifi, esp32 web server, esp32 webserver, webserver esp32, web server esp32, esp32 server mode

  • So, we are going to write the rest of our code in this IF loop.
  • AS you can see in the below code, if the client is available, we have printed “New Client” on Serial Monitor.
  • After that, we have a while loop checking for client connection, so as long as we have a connection with the client, we will remain in this loop.
  • Inside this while loop, we have an If loop, checking if the client is available.

esp32, esp32 wifi, esp32 web server, esp32 webserver, webserver esp32, web server esp32, esp32 server mode

  • Now, if we are connected to the client, we need to read for the incoming request.
  • So, If there are any bytes to read from the client, read those bytes:

esp32, esp32 wifi, esp32 web server, esp32 webserver, webserver esp32, web server esp32, esp32 server mode

  • The client request ends at New Line Character \n, so we are checking for that.
  • Once we received the New Line Character, we are sending the response back to the Client.
  • In response, we have first sent the HTTP header, which is the default for webpages so that browsers should understand the response type.

Checking Request Type

  • As we discussed earlier, on each button press, we are redirecting our client to its respective link.
  • Depending on which button is pushed, we make requests to different URLs to turn the LEDs on and off using if else statements, as shown below:

 

 

esp32, esp32 wifi, esp32 web server, esp32 webserver, webserver esp32, web server esp32, esp32 server mode

  • As you can see in the above code, we are repeating the same code three times for 3 LEDs.
  • In the first block, we are simply checking the header response and if it’s a GET request and from “/26/on”, we have turned that Pin HIGH, changed the LED state variable to “on” and sent a message on the serial monitor.
  • So, if a client clicks on the LED 26 ON button, ESP32 will understand the GET request and glow the LED.
  • The other buttons work in the same way. If you wish to add more outputs, you’ll need to change this section of the code.

 HTML to display a web page

  • We have designed the output part i.e. what we are going to do when a user clicks any button.
  • And now we are going to design those buttons themselves i.e. we are designing the webpage.
  • As you can see in the below figure, we have standard HTML tags at the start.
  • After that, we have some CSS text to design the buttons and the appearance of the web page. We use the Helvetica font and set the information to be shown as a block with the center aligned.
  • Next, displaying Web page heading i.e. “ESP32 Web Server”.

esp32, esp32 wifi, esp32 web server, esp32 webserver, webserver esp32, web server esp32, esp32 server mode

  • Next, comes the If Loop for the first Button, we are checking the LED state variable and based on LED state, we are displaying our Button.
  • So, if the LED state is OFF, we are redirecting the user to /LED_BUILTIN/on and vice versa.
  • That’s how we are changing the Buttons on the webpage, as you can see buttons are using different CSS classes for on and off states.
  • Similar loops are used to display the states on other connected LEDs.
  • Finally, we are closing the web connection and clearing the header that was used to store the HTTP request header using client.stop() function.
  • Printing information about the closed web connection on the serial monitor.

Uploading Web Server Code to ESP32

  • Please reread the previous instruction, “Introduction to ESP32 programming series,” if you are unfamiliar with the procedure of uploading code in the Arduino IDE.
  • After uploading the code, open the Serial Monitor with a baud rate of 115200.
  • Enable the ESP32 by pressing the EN (enable) button. The ESP32 establishes a Wi-Fi connection and the Serial Monitor displays the ESP32 IP address. To connect to the ESP32 web server, you’ll need that IP address.

esp32, esp32 wifi, esp32 web server, esp32 webserver, webserver esp32, web server esp32, esp32 server mode

Note:

  • Make sure you have selected the right board and COM port.

Getting IP address and Access ESP32 web Server

  • After successfully uploading the code in esp32 module.
  • Open Serial Monitor from the top right corner of Arduino IDE screen as shown in figure below:

esp32, esp32 wifi, esp32 web server, esp32 webserver, webserver esp32, web server esp32, esp32 server mode

  • The IP address required to connect to the ESP32 point will be displayed on the Serial Monitor. It’s 192.168.43.223 in this scenario.

 

esp32, esp32 wifi, esp32 web server, esp32 webserver, webserver esp32, web server esp32, esp32 server mode

  • To access the webserver, type the IP Address of the ESP32 into a Web Browser on a laptop or a mobile phone. It’s 192.168.43.223 in our case.
  • You should be able to see a simple web page served by the ESP32’s Web Server if everything goes well.

A screenshot of a Web Browser on a laptop accessing the ESP32 Web Server is shown below.

  • The image below is displaying the ON state of the inbuilt LED.
  • The inbuilt LED is Blue in color.

esp32, esp32 wifi, esp32 web server, esp32 webserver, webserver esp32, web server esp32, esp32 server mode

  • The below image is displaying the OFF State of the inbuilt LED

esp32, esp32 wifi, esp32 web server, esp32 webserver, webserver esp32, web server esp32, esp32 server mode

Using the ESP32 web server and the preceding process, you can control the peripherals linked to the ESP32 module from any mobile, tablet, or computer. The only need is that all of the devices to be linked to the same network.

This concludes the lesson. I hope it becomes useful to you. In the next tutorial, we will have a look at How to work the ESP32 BLE, so stay tuned. Have a good day. 🙂

Leave a Reply

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

Post comment