Project 8 : ESP32 Using Web Server

    ヾ(^∇^) ヾ(^∇^) ヾ(^∇^) ヾ(^∇^) ヾ(^∇^)

Starting a project is no small feat,

It takes a plan and lots of heat.

Gather ideas and get them neat,

Then put them down, don't miss a beat.


With every step, keep moving forward,

Don't let obstacles make you cornered.

Stay focused and you'll be rewarded,

A successful project is what's ordered.

    ヾ(^∇^) ヾ(^∇^) ヾ(^∇^) ヾ(^∇^) ヾ(^∇^)

👋👋👋 Hello guys, welcome back to my blogspot, this time we will make a project about using a web server to control esp 32 input output . For that without lingering any longer we just go into the project! 👊😀




------------------------------------------------------===≡≡≡┌( ͝° ͜ʖ͡°)┘

📦SET UP📦

1. 1 Pcs of ESP32


2.4 Pcs of Male to Male Cable Jumper
3. 3 Pcs of Male to Female Cable Jumper



4. 2 Pcs of 5 mm Led Lamp (Blue and Red Color)

5. 2 Pcs of 330 Ohm Resistor


6. 1 Pcs of Micro USB cable


7. 1 Pcs Of .Barometetric Pressure Sensor (BMP280)



1.ESP32 Web Server – Arduino IDE

"The way this project works is by visiting the website by entering the IP address into our browser. Then clicking the on button to turn on the light according to the relevant button then pressing the off button to turn off the corresponding LED light. Then there is an additional feature, namely the tooltip text that will appear when we hover one of the on / off buttons for the two lights. This tooltip text will provide a brief description of how the button works on our website."

👣 STEP BY STEP 👣

1.Create circuit schema based on picture below


Source : https://randomnerdtutorials.com/esp32-web-server-arduino-ide/

2.Use this code below in your arduino IDE .
/*********
  Rui Santos
  Complete project details at https://randomnerdtutorials.com  
*********/

// Load Wi-Fi library
#include <WiFi.h>

// Replace with your network credentials
const char* ssid = "AFI 1.";
const char* password = "tubagus1";

// 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.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;position: relative;display: inline-block;}");
            client.println(".button .tooltiptext , .button2 .tooltiptext {visibility: hidden;width: 120px;background-color: black;color: #fff;text-align: center;border-radius: 6px;padding: 5px 5px;");
            client.println("position: absolute;z-index: 1;top: -5px;left: 105%;}");
            client.println(".button:hover .tooltiptext , .button2:hover .tooltiptext {visibility: visible;}");
            client.println(" h1{background-color: rgb(107, 55, 204); color: white;}");
            client.println(".button2 {background-color: #555555;position: relative;display: inline-block;}</style></head>");
           
            // Web Page Heading
            client.println("<body><h1>Marvel Web Server</h1>");
           
            // Display current state, and ON/OFF buttons for GPIO 26  
            client.println("<p>RED LED - 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<span class=\"tooltiptext\">Click to Turn ON the LED</span></button></a></p>");
            } else {
              client.println("<p><a href=\"/26/off\"><button class=\"button button2\">OFF<span class=\"tooltiptext\">Click to Turn OFF the LED</span></button></a></p>");
            }
               
            // Display current state, and ON/OFF buttons for GPIO 27  
            client.println("<p>GREEN LED - 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<span class=\"tooltiptext\">Click to Turn ON the LED</span></button></a></p>");
            } else {
              client.println("<p><a href=\"/27/off\"><button class=\"button button2\">OFF<span class=\"tooltiptext\">Click to Turn OFF the LED</span></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("");
  }
}

3.Setting Your Network Credentials with set up the WIFI SSID and WIFI password in this section code below .

// Replace with your network credentials
const char* ssid = "AFI 1.";
const char* password = "tubagus1";

In this project , my wifi SSID is "AFI 1." and my wifi password is "tubagus1" .

4. Plug your ESP32 board in your computer

5.In the Arduino IDE select your board in Tools , the click "Board" (in this case i will choose DOIT ESP32 DEVKIT V1). You can see the details in image shown below.


6. Select the COM port in Tools > Port (In this case i will using COM3 Port).



7.Click the Upload button and wait a few seconds for the words "Leaving... Hard resetting via RTS pin..." to display. 



8.After uploading the code, open the Serial Monitor at a baud rate of 115200 and press the ESP32 EN button (reset).


9.Copy that IP address displayed in serial monitor .

10.Open your browser / google chrome / safari / etc , paste the ESP32 IP address that have been copied, and you’ll see the following page.



2.ESP32 Web Server – Arduino IDE

"This project will show the bmp280 sensor readings using a web server, which means we will see these readings on the website using the configured IP address. The readings will include temperature in Celsius, temperature in Fahrenheit, pressure, and estimated altitude."

👣 STEP BY STEP 👣

1.Create circuit schema based on picture below


source : https://www.circuitschools.com/interfacing-bmp280-with-esp-32-on-i2c-with-errors-and-solutions/


2.Use this code below in your arduino IDE .
/*********
  Rui Santos
  Complete project details at https://randomnerdtutorials.com  
*********/

// Load Wi-Fi library
#include <WiFi.h>
#include <Wire.h>
#include <Adafruit_BMP280.h>
#include <Adafruit_Sensor.h>

//uncomment the following lines if you're using SPI
/*#include <SPI.h>
#define BMP_SCK 18
#define BMP_MISO 19
#define BMP_MOSI 23
#define BMP_CS 5*/

#define SEALEVELPRESSURE_HPA (1013.25)

Adafruit_BMP280 bmp; // I2C
//Adafruit_BMP280 BMP(BMP_CS); // hardware SPI
//Adafruit_BMP280 BMP(BMP_CS, BMP_MOSI, BMP_MISO, BMP_SCK); // software SPI

// Replace with your network credentials
const char* ssid     = "AFI 1.";
const char* password = "tubagus1";

// 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);
  bool status;

  // default settings
  // (you can also pass in a Wire library object like &Wire2)
  //status = BMP.begin();  

    if (!bmp.begin(0x76))
  {  
    Serial.println("Could not find a valid BMP280 sensor, check wiring!");
    while (1);
  }
  Serial.println("Found BMP280 sensor!");


  // 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();
           
            // 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 table
            client.println("<style>body { text-align: center; font-family: \"Trebuchet MS\", Arial;}");
            client.println("table { border-collapse: collapse; width:35%; margin-left:auto; margin-right:auto; }");
            client.println("th { padding: 12px; background-color: #0043af; color: white; }");
            client.println("tr { border: 1px solid #ddd; padding: 12px; }");
            client.println("tr:hover { background-color: #bcbcbc; }");
            client.println("td { border: none; padding: 12px; }");
            client.println(".sensor { color:white; font-weight: bold; background-color: #bcbcbc; padding: 1px; }");
           
            // Web Page Heading
            client.println("</style></head><body><h1>ESP32 with BMP280</h1>");
            client.println("<table><tr><th>MEASUREMENT</th><th>VALUE</th></tr>");
            client.println("<tr><td>Temp. Celsius</td><td><span class=\"sensor\">");
            client.println(bmp.readTemperature());
            client.println(" *C</span></td></tr>");  
            client.println("<tr><td>Temp. Fahrenheit</td><td><span class=\"sensor\">");
            client.println(1.8 * bmp.readTemperature() + 32);
            client.println(" *F</span></td></tr>");      
            client.println("<tr><td>Pressure</td><td><span class=\"sensor\">");
            client.println(bmp.readPressure() / 100.0F);
            client.println(" hPa</span></td></tr>");
            client.println("<tr><td>Approx. Altitude</td><td><span class=\"sensor\">");
            client.println(bmp.readAltitude(SEALEVELPRESSURE_HPA));
            client.println(" m</span></td></tr>");
            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("");
  }
}

3.Setting Your Network Credentials with set up the WIFI SSID and WIFI password in this section code below .

// Replace with your network credentials
const char* ssid = "AFI 1.";
const char* password = "tubagus1";

In this project , my wifi SSID is "AFI 1." and my wifi password is "tubagus1" .

4. Plug your ESP32 board in your computer

5.In the Arduino IDE select your board in Tools , the click "Board" (in this case i will choose DOIT ESP32 DEVKIT V1). You can see the details in image shown below.

6. Select the COM port in Tools > Port (In this case i will using COM3 Port).


7.Click the Upload button and wait a few seconds for the words "Leaving... Hard resetting via RTS pin..." to display. 



8.After uploading the code, open the Serial Monitor at a baud rate of 115200 and press the ESP32 EN button (reset).



9.Copy that IP address displayed in serial monitor .

10.Open your browser / google chrome / safari / etc , paste the ESP32 IP address that have been copied, and you’ll see the following page.




d( ̄◇ ̄)b .....Hooray, we've finished the project 

😄That's all from me 👌

👋 See you in my next blog with ESP32. 

👋 Bye Bye !





Comments

Popular posts from this blog

Project 7 : Connecting ESP32 and our smartphone with bluetooth connection