Thứ Bảy, 23 tháng 8, 2025

Chat GPT viết điều khiển 2 LED bằng ESP 8266 qua điện thoại

 Bạn hãy mở ứng dụng Arduino lên, nhập đoạn mã sau và nạp vào ESP8266.

Mở điện thoại truy cập vào Wifi của ESP tên: ESP8266_AP, nhập mật khẩu: 12345678



Sau đó dùng trình duyệt web, nhập vào địa chỉ 192.168.4.1 để vào điều khiển 2 đèn LED có sẵn trên ESP8266 NodeMCU 1.0

#include <ESP8266WiFi.h>
#include <ESP8266WebServer.h>
#include <EEPROM.h>

// Dung lượng EEPROM đủ để lưu SSID & PASS
#define EEPROM_SIZE 96   // 32 byte SSID + 64 byte PASS

ESP8266WebServer server(80);

// Chân LED
#define LED1 2
#define LED2 16

bool led1State = false;
bool led2State = true;

String ssid = "ESP8266_AP";   // SSID mặc định
String password = "12345678"; // PASS mặc định

// ====== Lưu và đọc WiFi vào EEPROM ======
void saveWiFiConfig(String s, String p) {
  EEPROM.begin(EEPROM_SIZE);

  // Ghi SSID (32 byte)
  for (int i = 0; i < 32; i++) {
    if (i < s.length()) EEPROM.write(i, s[i]);
    else EEPROM.write(i, 0);
  }

  // Ghi PASS (64 byte)
  for (int i = 0; i < 64; i++) {
    if (i < p.length()) EEPROM.write(32 + i, p[i]);
    else EEPROM.write(32 + i, 0);
  }

  EEPROM.commit();
  EEPROM.end();
}

void loadWiFiConfig() {
  EEPROM.begin(EEPROM_SIZE);

  char s[33], p[65];
  for (int i = 0; i < 32; i++) s[i] = EEPROM.read(i);
  s[32] = '\0';
  for (int i = 0; i < 64; i++) p[i] = EEPROM.read(32 + i);
  p[64] = '\0';

  EEPROM.end();

  if (String(s).length() > 0) ssid = String(s);
  if (String(p).length() > 0) password = String(p);
}

// ====== HTML giao diện ======
String htmlPage() {
  String html = R"rawliteral(
  <!DOCTYPE html>
  <html lang="vi">
  <head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Điều khiển LED + WiFi</title>
    <style>
      body { font-family: Arial; background: #001f3f; color: white; text-align: center; margin: 0; padding: 20px; }
      h1 { color: #FFD700; }
      .btn { padding: 15px 30px; margin: 10px; font-size: 18px; border-radius: 10px; cursor: pointer; }
      .on { background: #28a745; color: white; box-shadow: 0 0 20px #28a745; }
      .off { background: #6c757d; color: white; opacity: 0.6; }
      .form-container { margin-top: 40px; background: #003366; padding: 20px; border-radius: 15px; }
      input { padding: 12px; margin: 10px 0; width: 80%; border-radius: 8px; border: none; font-size: 16px; }
      .save-btn { padding: 12px 25px; font-size: 16px; border-radius: 10px; background: #FF4500; color: white; cursor: pointer; }
    </style>
  </head>
  <body>
    <h1>🌟Điều khiển 2 LED🌟</h1>
    <button class="btn %LED1%" onclick="toggleLED(1)">LED 1</button>
    <button class="btn %LED2%" onclick="toggleLED(2)">LED 2</button>
    <div class="form-container">
      <h2>⚙️ Đổi tên Wifi & Mật khẩu</h2>
      <form action="/setwifi" method="POST">
        <input type="text" name="ssid" placeholder="Tên WiFi mới (SSID)" required><br>
        <input type="password" name="pass" placeholder="Mật khẩu mới" required><br>
        <button type="submit" class="save-btn">💾 Lưu cài đặt</button>
      </form>
      <p><i>(ESP8266 sẽ tự động khởi động lại để áp dụng WiFi mới)</i></p>
    </div>
    <script>
      function toggleLED(led) {
        fetch('/led?num=' + led).then(()=>{location.reload();});
      }
    </script>
  </body>
  </html>
  )rawliteral";

  html.replace("%LED1%", led1State ? "on" : "off");
  html.replace("%LED2%", led2State ? "on" : "off");
  return html;
}

// ====== Xử lý request ======
void handleRoot() {
  server.send(200, "text/html; charset=utf-8", htmlPage());
}

void handleLED() {
  if (server.hasArg("num")) {
    int ledNum = server.arg("num").toInt();
    if (ledNum == 1) { led1State = !led1State; digitalWrite(LED1, led1State ? LOW : HIGH); }
    else if (ledNum == 2) { led2State = !led2State; digitalWrite(LED2, led2State ? LOW : HIGH); }
  }
  server.sendHeader("Location", "/");
  server.send(303);
}

void handleSetWiFi() {
  if (server.method() == HTTP_POST) {
    String newSSID = server.arg("ssid");
    String newPASS = server.arg("pass");

    // Lưu vào EEPROM
    saveWiFiConfig(newSSID, newPASS);

    String msg = "<html><body><h2>✅ Đã lưu WiFi mới!</h2>";
    msg += "<p>SSID: " + newSSID + "</p>";
    msg += "<p>Password: " + newPASS + "</p>";
    msg += "<p>ESP8266 sẽ khởi động lại...</p>";
    msg += "</body></html>";
    server.send(200, "text/html; charset=utf-8", msg);

    delay(1000);
    ESP.restart(); // Reset lại ESP để áp dụng
  }
}

// ====== Setup ======
void setup() {
  Serial.begin(115200);

  pinMode(LED1, OUTPUT);
  pinMode(LED2, OUTPUT);
  digitalWrite(LED1, HIGH);
  digitalWrite(LED2, HIGH);

  // Đọc WiFi đã lưu từ EEPROM
  loadWiFiConfig();

  // Phát AP
  WiFi.softAP(ssid.c_str(), password.c_str());
  Serial.println("WiFi AP: " + ssid);
  Serial.println("IP: " + WiFi.softAPIP().toString());

  server.on("/", handleRoot);
  server.on("/led", handleLED);
  server.on("/setwifi", handleSetWiFi);
  server.begin();
}

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


Không có nhận xét nào:

Đăng nhận xét