ESP32 sebagai Web Server

Kali ini kita akan buat ESP32 sebagai web server. Program nya adalah sebagai berikut. Pada baris program di bawah ini disertakan juga link-link yang bisa dipelajari lebbih detail mengenai perintah-perintah yang digunakan pada program

/*
ESP32 sebagai web server

Link yang berhubungan :
https://arduino-esp8266.readthedocs.io/en/latest/esp8266wifi/soft-access-point-class.html
https://github.com/espressif/arduino-esp32/blob/master/libraries/WiFi/examples/WiFiAccessPoint/WiFiAccessPoint.ino

*/

#include <Arduino.h>
#include <WiFi.h>

// Replace with your network credentials
const char* ssid     = "ESP32-WebServer";
const char* password = "123456789";

// Set web server port number to 80
WiFiServer server(80);

// Variable to store the HTTP request
String header;

String htmlHead = "<!DOCTYPE html><html>\n"
                  "<head><meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n"
                  "<link rel=\"icon\" href=\"data:,\"></head>";

String htmlBody = "<body><h1>ESP32 sebagai Web Server</h1></body><html>";


void setup() {
  Serial.begin(115200);

  Serial.print("Setting AP (Access Point)…");
  WiFi.softAP(ssid, password);

  // IP Address untuk Access Point, default nya 192.168.4.1 
  IPAddress IP = WiFi.softAPIP();
  Serial.print("AP IP address: ");
  Serial.println(IP);
    
  server.begin();
}

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

  if (client) {                             // If a new client connects,
    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()) {            // loop while the client's connected
      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(htmlHead);
            client.println(htmlBody);

            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("");
  }
}

Setelah program di atas jalan, akan terlihat pada Serial Monitor seperti di bawah ini.

Setting AP (Access Point)…AP IP address: 192.168.4.1

Secara default, perintah

WiFi.softAP(ssid, password);

Akan membuat Board menjadi Acces Point dan IP Default yang diberikan adalah 192.168.4.1

Bisa dicoba menggunakan HP untuk connect ke SSID : ESP32-WebServer, lalu masukan password 123456789
Setelah WiFi terhubung, silahkan akses http://192.168.4.1

Cara setting AP juga dapat menggunakan perintah berikut

WiFi.softAP(ssid, psk, channel, hidden, max_connection)
  • ssid – Nama SSID (max. 32 karakter)
  • psk – pre-shared key. Untuk WPA2-PSK minimum 8 karakter and maksimum 64 karakter. Jika tidak diisi, maka siapapun bisa akses (WiFi bersifat Open).
  • channel – Wi-Fi channel, dari 1 sampai 13. Default channel = 1.
  • hidden – jika di set true , maka akan sembunyikan SSID.
  • max_connection – Maksimum yang bisa terkoneksi ke board , dari 0 sampai 8. Default nya 4. Saat maksimum koneksi terpenuhi, maka client yang akan terhubung, dipersilahkan untuk menunggu sampai ada client yang available.

Cara mengubah IP Address

Untuk mengubah IP Address Default, bisa definisikan IP Addressnya terlebih dahulu, misalnya seperti di bawah ini:

// Static IP Address
IPAddress local_IP(192, 168, 123, 2);
// Gateway IP address
IPAddress gateway(192, 168, 123, 1);
IPAddress subnet(255, 255, 255, 0);

Kemudian cara menggunakannya :

WiFi.softAPConfig(local_IP, gateway, subnet);
WiFi.softAP(ssid, password);

Program lengkap nya adalah sebagai berikut :

/*
ESP32 sebagai web server

Link yang berhubungan :
https://arduino-esp8266.readthedocs.io/en/latest/esp8266wifi/soft-access-point-class.html
https://github.com/espressif/arduino-esp32/blob/master/libraries/WiFi/examples/WiFiAccessPoint/WiFiAccessPoint.ino

*/

#include <Arduino.h>
#include <WiFi.h>

// Replace with your network credentials
const char* ssid     = "ESP32-WebServer-Static";
const char* password = "123456789";

// Static IP Address
IPAddress local_IP(192, 168, 123, 2);
// Set your Gateway IP address
IPAddress gateway(192, 168, 123, 1);
// Subnet yang diperbolehkan mulai /24 sampai /28
IPAddress subnet(255, 255, 255, 0);

// Set web server port number to 80
WiFiServer server(80);

// Variable to store the HTTP request
String header;

String htmlHead = "<!DOCTYPE html><html>\n"
                  "<head><meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n"
                  "<link rel=\"icon\" href=\"data:,\"></head>";

String htmlBody = "<body><h1>ESP32 sebagai Web Server dengan Static IP Address</h1></body><html>";


void setup() {
  Serial.begin(115200);

  Serial.print("Setting soft-AP dgn Static IP ... ");
  Serial.println(WiFi.softAPConfig(local_IP, gateway, subnet) ? "Ready" : "Failed!");

  Serial.print("Setting soft-AP ... ");
  Serial.println(WiFi.softAP(ssid, password) ? "Ready" : "Failed!");

  Serial.print("Soft-AP IP address = ");
  Serial.println(WiFi.softAPIP());
    
  server.begin();
}

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

  if (client) {                             // If a new client connects,
    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()) {            // loop while the client's connected
      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(htmlHead);
            client.println(htmlBody);

            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("");
  }
}

Leave a Comment

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