วิธีการสร้างโครงการควบคุม WiFi ESP32 (เว็บเซอร์วิส)

 

คุณสามารถสร้างเว็บเซอร์วิสโดยใช้บอร์ด ESP32 เพื่อควบคุมอุปกรณ์อิเล็กทรอนิกส์ภายในบ้าน ในบทความนี้ เราจะแสดงวิธีการสร้างเว็บเซอร์วิสพื้นฐานโดยใช้ ESP32 เพื่อควบคุมหลอดไฟ LED


เกี่ยวกับบอร์ด ESP32


ESP32 คือไมโครคอนโทรลเลอร์ System-on-a-Chip (SoC) ที่ได้รับความนิยม ใช้พลังงานต่ำ ราคาประหยัด พร้อมการเชื่อมต่อ Wi-Fi และ Bluetooth ผลิตโดย Espressif Systems และเป็นที่นิยมอย่างมากสำหรับโครงการ IoT (Internet of Things)


ความสามารถของ ESP32:


· โปรเซสเซอร์ดูอัลคอร์ (Xtensa LX6) ความเร็วสัญญาณนาฬิกาตั้งแต่ 160 MHz ถึง 240 MHz

· หน่วยความจำ SRAM และแฟลชแบบเต็ม

· รวม Wi-Fi 802.11 b/g/n (2.4 GHz) และ Bluetooth (แบบคลาสสิกและ BLE)

.  การเชื่อมต่อไร้สาย


ครั้งนี้ผมจะอธิบายวิธีการสร้างเว็บเซิร์ฟเวอร์ระดับมืออาชีพโดยใช้ไมโครคอนโทรลเลอร์ ESP32


วัสดุที่ต้องใช้สำหรับโครงการ:


. บอร์ดพัฒนา ESP32 หนึ่งตัว

. ตัวต้านทาน 220 โอห์มสองตัว

. หลอดไฟ LED สองหลอด

. สายจัมเปอร์


คุณสมบัติโครงการ


. UI/ดีไซน์สวยงาม

. ใช้งานได้ทั้งบนมือถือและเดสก์ท็อป

. สามารถควบคุมหลอดไฟ LED ได้จากเว็บเซิร์ฟเวอร์


แผนภาพฮาร์ดแวร์


เชื่อมต่อพิน 2 และ 4 ของ ESP32 เข้ากับขั้ว + ของ LED ทั้งสอง โดยแต่ละตัวมีตัวต้านทาน 220 โอห์ม ตามที่แสดงในภาพเชื่อมต่อพิน LED - เข้ากับพิน GND ของบอร์ด


รหัสบริการเว็บ


// Load Wi-Fi library

#include <WiFi.h>


// Network credentials Here

const char* ssid     = "ESP32-SSID";

const char* password = "Esp32-Password";


// Set web server port number to 80

WiFiServer server(80);


// Variable to store the HTTP request

String header;


//variables to store the current LED states

String statePin2 = "off";

String statePin4 = "off";

//Output variable to GPIO pins

const int ledPin2 = 2;

const int ledPin4 = 4;


// Current time

unsigned long currentTime = millis();

// Previous time

unsigned long previousTime = 0;

// Define timeout time in milliseconds

const long timeoutTime = 2000;


void setup() {

  Serial.begin(115200);

  

  // Initialize GPIO pins

  pinMode(ledPin2, OUTPUT);

  digitalWrite(ledPin2, LOW);

  pinMode(ledPin4, OUTPUT);

  digitalWrite(ledPin4, LOW);


  // Setup WiFi Access Point

  Serial.println("Setting up Access Point...");

  WiFi.softAP(ssid, password);

  

  // Print IP address and start web server

  Serial.println("");

  Serial.println("Access Point IP address: ");

  Serial.println(WiFi.softAPIP());

  server.begin();

  Serial.println("HTTP server started");

}


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

    header = "";                            // Clear header at start


    while (client.connected() && currentTime - previousTime <= timeoutTime) {

      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 /2/on") >= 0) {

              Serial.println("GPIO 2 ON");

              statePin2 = "on";

              digitalWrite(ledPin2, HIGH);

            } else if (header.indexOf("GET /2/off") >= 0) {

              Serial.println("GPIO 2 OFF");

              statePin2 = "off";

              digitalWrite(ledPin2, LOW);

            }

            

            if (header.indexOf("GET /4/on") >= 0) {

              Serial.println("GPIO 4 ON");

              statePin4 = "on";

              digitalWrite(ledPin4, HIGH);

            } else if (header.indexOf("GET /4/off") >= 0) {

              Serial.println("GPIO 4 OFF");

              statePin4 = "off";

              digitalWrite(ledPin4, LOW);

            }


            // Premium UI Design HTML

            client.println("<!DOCTYPE html><html lang='en'>");

            client.println("<head>");

            client.println("<meta charset='UTF-8'>");

            client.println("<meta name='viewport' content='width=device-width, initial-scale=1.0'>");

            client.println("<title>ESP32 Control Panel</title>");

            client.println("<link rel='icon' href='data:,'>");

            client.println("<style>");

            client.println("* { margin: 0; padding: 0; box-sizing: border-box; }");

            client.println("body { font-family: 'Segoe UI', system-ui, sans-serif; background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); min-height: 100vh; display: flex; justify-content: center; align-items: center; padding: 20px; }");

            client.println(".container { background: rgba(255, 255, 255, 0.95); backdrop-filter: blur(10px); border-radius: 24px; padding: 40px; box-shadow: 0 20px 40px rgba(0,0,0,0.1); max-width: 500px; width: 100%; text-align: center; border: 1px solid rgba(255,255,255,0.2); }");

            client.println(".header { margin-bottom: 30px; }");

            client.println(".header h1 { color: #2d3748; font-size: 2.5em; font-weight: 700; margin-bottom: 8px; background: linear-gradient(135deg, #667eea, #764ba2); -webkit-background-clip: text; -webkit-text-fill-color: transparent; }");

            client.println(".header p { color: #718096; font-size: 1.1em; font-weight: 400; }");

            client.println(".control-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 25px; margin: 35px 0; }");

            client.println(".control-card { background: white; border-radius: 20px; padding: 30px; box-shadow: 0 8px 25px rgba(0,0,0,0.08); transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1); border: 1px solid #e2e8f0; position: relative; overflow: hidden; }");

            client.println(".control-card::before { content: ''; position: absolute; top: 0; left: 0; right: 0; height: 4px; background: linear-gradient(90deg, #667eea, #764ba2); }");

            client.println(".control-card:hover { transform: translateY(-8px); box-shadow: 0 15px 35px rgba(0,0,0,0.15); }");

            client.println(".led-title { font-size: 1.4em; color: #2d3748; margin-bottom: 20px; font-weight: 600; display: flex; align-items: center; justify-content: center; gap: 10px; }");

            client.println(".status-indicator { display: flex; align-items: center; justify-content: center; gap: 12px; margin: 20px 0; padding: 12px; border-radius: 12px; background: #f7fafc; }");

            client.println(".status-dot { width: 16px; height: 16px; border-radius: 50%; transition: all 0.3s ease; }");

            client.println(".status-dot.on { background: #48bb78; box-shadow: 0 0 12px #48bb78; }");

            client.println(".status-dot.off { background: #a0aec0; }");

            client.println(".status-text { font-size: 1em; font-weight: 600; color: #4a5568; }");

            client.println(".btn { background: linear-gradient(135deg, #48bb78, #38a169); border: none; color: white; padding: 18px 35px; font-size: 1.1em; font-weight: 600; border-radius: 14px; cursor: pointer; transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1); text-decoration: none; display: inline-block; box-shadow: 0 6px 20px rgba(72, 187, 120, 0.3); position: relative; overflow: hidden; }");

            client.println(".btn::before { content: ''; position: absolute; top: 0; left: -100%; width: 100%; height: 100%; background: linear-gradient(90deg, transparent, rgba(255,255,255,0.3), transparent); transition: left 0.5s; }");

            client.println(".btn:hover::before { left: 100%; }");

            client.println(".btn:hover { transform: translateY(-3px); box-shadow: 0 10px 25px rgba(72, 187, 120, 0.4); }");

            client.println(".btn:active { transform: translateY(-1px); }");

            client.println(".btn.off { background: linear-gradient(135deg, #f56565, #e53e3e); box-shadow: 0 6px 20px rgba(245, 101, 101, 0.3); }");

            client.println(".btn.off:hover { box-shadow: 0 10px 25px rgba(245, 101, 101, 0.4); }");

            client.println(".footer { margin-top: 30px; color: #a0aec0; font-size: 0.9em; }");

            client.println("@media (max-width: 600px) { .control-grid { grid-template-columns: 1fr; } .container { padding: 25px; } }");

            client.println("</style>");

            client.println("</head>");

            client.println("<body>");

            client.println("<div class='container'>");

            client.println("<div class='header'>");

            client.println("<h1>ESP32 Control Panel</h1>");

            client.println("<p>Premium LED Control Interface</p>");

            client.println("</div>");

            client.println("<div class='control-grid'>");

            

            // GPIO 2 Control Card

            client.println("<div class='control-card'>");

            client.println("<div class='led-title'>");

            client.println("<span>LED 2</span>");

            client.println("</div>");

            client.println("<div class='status-indicator'>");

            client.print("<div class='status-dot ");

            client.print(statePin2);

            client.println("'></div>");

            client.print("<span class='status-text'>");

            client.print(statePin2);

            client.println("</span>");

            client.println("</div>");

            if (statePin2 == "off") {

              client.println("<a href='/2/on' class='btn'>Turn ON</a>");

            } else {

              client.println("<a href='/2/off' class='btn off'>Turn OFF</a>");

            }

            client.println("</div>");

            

            // GPIO 4 Control Card

            client.println("<div class='control-card'>");

            client.println("<div class='led-title'>");

            client.println("<span>LED 4</span>");

            client.println("</div>");

            client.println("<div class='status-indicator'>");

            client.print("<div class='status-dot ");

            client.print(statePin4);

            client.println("'></div>");

            client.print("<span class='status-text'>");

            client.print(statePin4);

            client.println("</span>");

            client.println("</div>");

            if (statePin4 == "off") {

              client.println("<a href='/4/on' class='btn'>Turn ON</a>");

            } else {

              client.println("<a href='/4/off' class='btn off'>Turn OFF</a>");

            }

            client.println("</div>");

            client.println("</div>");

            client.println("<div class='footer'>");

            client.println("<p>ESP32 Web Server &bull; Premium Edition</p>");

            client.println("</div>");

            client.println("</div>");

            client.println("</body>");

            client.println("</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("");

  }

}


โค้ดด้านบนได้รับการเตรียมไว้เพื่อใช้งานไม่เพียงแต่ใน Arduino IDE เท่านั้น แต่ยังรวมถึง Arduinodroid ด้วยในโค้ดด้านบนนี้ใช้รหัส PIN หมายเลข 2 และ 4 คุณยังสามารถตั้งค่า SSID และรหัสผ่านสำหรับ Wi-Fi ได้ด้วย


วิธีอัพโหลดโปรแกรม

ขั้นตอนที่ 1

คัดลอกโค้ดด้านบนไปยัง Arduino IDE หรือ Arduinodroid


ขั้นตอนที่ 2

เลือกประเภทบอร์ด ESP32 ที่คุณต้องการใช้ใน Arduino IDE และคอมไพล์โค้ด


ขั้นตอนที่ 3

คุณสามารถอัปโหลดโปรแกรมไปยังบอร์ด ESP32 จาก ArduinoIDE และใช้งานได้


ขั้นตอนที่ 4
หากการอัปโหลดโปรแกรมสำเร็จ คุณสามารถเปิดพอร์ตอนุกรมของ IDE และกดปุ่ม EN (Reset) ของ ESP32 เพื่อตรวจสอบที่อยู่ IP เมื่อทราบที่อยู่ IP แล้ว คุณสามารถเชื่อมต่อกับ Wi-Fi โดยใช้ SSID และรหัสผ่านที่คุณระบุไว้ในรหัส และใช้เบราว์เซอร์เพื่อควบคุมหลอดไฟ LED

ตอนนี้คุณสามารถสร้างโครงการเว็บเซอร์วิสของคุณได้โดยใช้วิธีการข้างต้น

Post a Comment

© Delta Coder. All rights reserved. Distributed by Pixabin