ESP32/8266 WEB SERVER

What is a Web Server?

The web server is a place to send and receive information, process the information and store it. The web server can also display this information on a web page.

the server communicates with the user through a protocol called the Hypertext Transfer Protocol (HTTP).

When a request is sent to this server (for example, its address is searched in the browser), the server returns a code as a response (for example, code 200, which means the connection is established correctly, or code 404, which indicates that the address is not correct). You can find the full list of these codes here

Programming Code Explanation

In this case, the ESP32 module is connected to the Wi-Fi router as a Client and can access the Internet through the router.

code

To start the ESP32 in STA mode, just upload the following code on the board.

/*
  ESP32 Web Server - STA Mode
  modified on 25 MAy 2019
  by Mohammadreza Akbari @ Electropeak
  https://electropeak.com/learn
*/

#include <WiFi.h>
#include <WebServer.h>

// SSID & Password
const char* ssid = "*****";  // Enter your SSID here
const char* password = "*****";  //Enter your Password here

WebServer server(80);  // Object of WebServer(HTTP port, 80 is defult)

void setup() {
  Serial.begin(115200);
  Serial.println("Try Connecting to ");
  Serial.println(ssid);

  // Connect to your wi-fi modem
  WiFi.begin(ssid, password);

  // Check wi-fi is connected to wi-fi network
  while (WiFi.status() != WL_CONNECTED) {
  delay(1000);
  Serial.print(".");
  }
  Serial.println("");
  Serial.println("WiFi connected successfully");
  Serial.print("Got IP: ");
  Serial.println(WiFi.localIP());  //Show ESP32 IP on serial

  server.on("/", handle_root);

  server.begin();
  Serial.println("HTTP server started");
  delay(100);
}

void loop() {
  server.handleClient();
}

// HTML & CSS contents which display on web server
String HTML = "<!DOCTYPE html>\
<html>\
<body>\
<h1>My First Web Server with ESP32 - Station Mode &#128522;</h1>\
</body>\
</html>";

// Handle root url (/)
void handle_root() {
  server.send(200, "text/html", HTML);
}

Once you’ve uploaded the code, open the serial monitor window. If you’ve entered the correct SSID and password, after a few seconds, ESP32 will connect to the router and give you an IP address.

Check that you are using the proper baudrate to read the serial monitor properly

By entering this IP in your browser you can see the web page you have just created.

Your device should be in the same wifi network as the ESP

About the Code:

#include <WiFi.h>
#include <WebServer.h>

Two required libraries have been added at the beginning of the code. The WiFi.h library is used to set up the wifi section and WebServer.h library to build a web page.

const char* ssid = "****";
const char* password = "****";

Enter the SSID and the password of your router in these two lines.

WebServer server(80);

This command defines an object called the server from the webserver class. With this object, you can create a web page on Port 80.

In the setup section, serial communication is initially started.

WiFi.begin(ssid, password);

With the WiFi.begin command, ESP32 attempts to connect to your wifi router with the SSID and the password that is defined in the code.

while (WiFi.status() != WL_CONNECTED) {
  delay(1000);
  Serial.print(".");
  }
  Serial.println("");
  Serial.println("WiFi connected successfully");

The above code print the “.” carachter on the serial monitor until the ESP32 is connected to the Wi-Fi router. When the connection is established correctly, “WiFi connected successfully” is displayed on the serial monitor.

Serial.print("Got IP: ");
Serial.println(WiFi.localIP());

Then the IP address of ESP32 will be printed on the serial monitor.

To manage HTTP requests and specify what part of the code to run when a URL address is searched, the on method is used.

server.on("/", handle_root);

In the above code, when the main address (place a / after the IP) is searched in the browser, the handle_root function is called.

Finally, with the server. begin command, your web server starts working.

In the loop section, only the handleClient method is called, so your code (the server that you built) is always checking the web server to manage the events occurring on the server.

String HTML = "<!DOCTYPE html>\
<html>\
<body>\
<h1>My First Web Server with ESP32 - Station Mode &#128522;</h1>\
</body>\
</html>";

The HTML string contains the code that should be displayed on the web page. At the end of this tutorial, you can find a basic tutorial on HTML coding for beginners.

Tip To write a command in a few lines, just add a backslash () at the end of each line.

void handle_root() {

  server.send(200, "text/html", HTML);
}

The handle_root unction is called whenever the main path (the IP address) is searched in the browser. In this function, the send method is used.

The send command sends the code number 200 (that means the page is opened correctly), along with the HTML code we wrote, to display it on the web page.

Concept Behind Controlling Things From ESP32 Web Server

So, you might be thinking, “How am I going to control things from a web server that merely processes and delivers web pages?” Well, then you need to understand what’s going on behind the scene.

When you type a URL in a web browser and hit ENTER, the browser sends a HTTP request (a.k.a. GET request) to a web server. It’s a job of web server to handle this request by doing something. You might have figured it out by now that we are going to control things by accessing a specific URL. For example, suppose we entered a URL like http://192.168.1.1/ledon in a browser. The browser then sends a HTTP request to ESP32 to handle this request. When ESP32 reads this request, it knows that user wants to turn the LED ON. So, it turns the LED ON and sends a dynamic webpage to a browser showing LED status : ON. As easy as Pie!

Now, click the button to turn LED1 ON while keeping an eye on the URL. Once you click the button, the ESP32 receives a request for /led1on URL. It then turns the LED1 ON and serves a web page with status of LED updated. It also prints the status of GPIO pin on the serial monitor.

You can test LED2 button and check that it works in a similar way.

Now, let’s take a closer look at the code to see how it works, so that you are able to modify it to fulfill your needs.

ESP32 as HTTP Server with buttons using WiFi Station (STA) mode

Example wiring

Now that we know the basics of how web server works, and in which modes ESP32 can create a web server, it’s time to connect some LEDs to ESP32 that we want to control over WiFi.

Code

#include <WiFi.h>
#include <WebServer.h>

/*Put your SSID & Password*/
const char* ssid = " YourNetworkName";  // Enter SSID here
const char* password = " YourPassword";  //Enter Password here

WebServer server(80);

uint8_t LED1pin = 4;
bool LED1status = LOW;

uint8_t LED2pin = 5;
bool LED2status = LOW;

void setup() {
  Serial.begin(115200);
  delay(100);
  pinMode(LED1pin, OUTPUT);
  pinMode(LED2pin, OUTPUT);

  Serial.println("Connecting to ");
  Serial.println(ssid);

  //connect to your local wi-fi network
  WiFi.begin(ssid, password);

  //check wi-fi is connected to wi-fi network
  while (WiFi.status() != WL_CONNECTED) {
  delay(1000);
  Serial.print(".");
  }
  Serial.println("");
  Serial.println("WiFi connected..!");
  Serial.print("Got IP: ");  Serial.println(WiFi.localIP());

  server.on("/", handle_OnConnect);
  server.on("/led1on", handle_led1on);
  server.on("/led1off", handle_led1off);
  server.on("/led2on", handle_led2on);
  server.on("/led2off", handle_led2off);
  server.onNotFound(handle_NotFound);

  server.begin();
  Serial.println("HTTP server started");
}
void loop() {
  server.handleClient();
  if(LED1status)
  {digitalWrite(LED1pin, HIGH);}
  else
  {digitalWrite(LED1pin, LOW);}

  if(LED2status)
  {digitalWrite(LED2pin, HIGH);}
  else
  {digitalWrite(LED2pin, LOW);}
}

void handle_OnConnect() {
  LED1status = LOW;
  LED2status = LOW;
  Serial.println("GPIO4 Status: OFF | GPIO5 Status: OFF");
  server.send(200, "text/html", SendHTML(LED1status,LED2status));
}

void handle_led1on() {
  LED1status = HIGH;
  Serial.println("GPIO4 Status: ON");
  server.send(200, "text/html", SendHTML(true,LED2status));
}

void handle_led1off() {
  LED1status = LOW;
  Serial.println("GPIO4 Status: OFF");
  server.send(200, "text/html", SendHTML(false,LED2status));
}

void handle_led2on() {
  LED2status = HIGH;
  Serial.println("GPIO5 Status: ON");
  server.send(200, "text/html", SendHTML(LED1status,true));
}

void handle_led2off() {
  LED2status = LOW;
  Serial.println("GPIO5 Status: OFF");
  server.send(200, "text/html", SendHTML(LED1status,false));
}

void handle_NotFound(){
  server.send(404, "text/plain", "Not found");
}

String SendHTML(uint8_t led1stat,uint8_t led2stat){
  String ptr = "<!DOCTYPE html> <html>\n";
  ptr +="<head><meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0, user-scalable=no\">\n";
  ptr +="<title>LED Control</title>\n";
  ptr +="<style>html { font-family: Helvetica; display: inline-block; margin: 0px auto; text-align: center;}\n";
  ptr +="body{margin-top: 50px;} h1 {color: #444444;margin: 50px auto 30px;} h3 {color: #444444;margin-bottom: 50px;}\n";
  ptr +=".button {display: block;width: 80px;background-color: #3498db;border: none;color: white;padding: 13px 30px;text-decoration: none;font-size: 25px;margin: 0px auto 35px;cursor: pointer;border-radius: 4px;}\n";
  ptr +=".button-on {background-color: #3498db;}\n";
  ptr +=".button-on:active {background-color: #2980b9;}\n";
  ptr +=".button-off {background-color: #34495e;}\n";
  ptr +=".button-off:active {background-color: #2c3e50;}\n";
  ptr +="p {font-size: 14px;color: #888;margin-bottom: 10px;}\n";
  ptr +="</style>\n";
  ptr +="</head>\n";
  ptr +="<body>\n";
  ptr +="<h1>ESP32 Web Server</h1>\n";
    ptr +="<h3>Using Station(STA) Mode</h3>\n";

   if(led1stat)
  {ptr +="<p>LED1 Status: ON</p><a class=\"button button-off\" href=\"/led1off\">OFF</a>\n";}
  else
  {ptr +="<p>LED1 Status: OFF</p><a class=\"button button-on\" href=\"/led1on\">ON</a>\n";}

  if(led2stat)
  {ptr +="<p>LED2 Status: ON</p><a class=\"button button-off\" href=\"/led2off\">OFF</a>\n";}
  else
  {ptr +="<p>LED2 Status: OFF</p><a class=\"button button-on\" href=\"/led2on\">ON</a>\n";}

  ptr +="</body>\n";
  ptr +="</html>\n";
  return ptr;
}

The only difference between AP & STA mode is one creates the network and other joins the existing network. So, rest of the code for handling HTTP requests and serving web page in STA mode is same as that of AP mode explained above. This includes:

Already coded button in a minimal interface

Link to github repo code

ESP WEB SERVER + BOOTSTRAP

Link to code

ESP WEB SERVER + BOOTSTRAP FAB BLIMP Control

LINK TO THE REPO

VIDEO LINK

ESP SPIFFS MEMORY

Link to tutorial Link to tutorial