Hướng dẫn Update Code OTA cho ESP32

Bước 1: Nạp code cho esp32
Bước 2: Chỉnh sửa code hiện tại
Bước 3: Kết nối wifi với ESP32

Bước 4: Truy cập đường dần 192.168.4.1/update

Bước 5: Tiến hành Update thôi! Chúc các bạn cập nhật thành công.
Chú ý: Ở đầu file ae thay 3 dòng include thêm 3 thư viện này nhé.
WiFi.h
WebServer.h
ElegantOTA.h
 



#include 
#include 
#include 
const char* ssid     = "ESP32-UPDATE-AP";
const char* password = "12345678";
const int btnPin     = 0;    // GPIO0, kéo lên sẵn (INPUT_PULLUP)
const int ledPin     = 26;   // LED báo trạng thái
bool otaMode         = false;

WebServer server(80);

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

  // 1) Khởi tạo nút và LED
  pinMode(btnPin, INPUT_PULLUP);
  pinMode(ledPin, OUTPUT);
  digitalWrite(ledPin, LOW);

  // 2) Kiểm tra giữ nút GPIO0 thấp 5s để vào chế độ OTA
  Serial.println("Giữ GPIO0 (LOW) liên tục 5s để vào OTA mode...");
  unsigned long start = millis();
  while (millis() - start < 6000) { if (digitalRead(btnPin) == LOW) { // nếu đã giữ đủ 5s if (millis() - start >= 5000) {
        otaMode = true;
        break;
      }
    } else {
      // thả nút, reset timer
      start = millis();
    }
    delay(10);
  }

  // 3) Nếu vào OTA mode thì khởi AP + ElegantOTA
  if (otaMode) {
    digitalWrite(ledPin, HIGH);
    WiFi.softAP(ssid, password);
    Serial.println("-> OTA mode: AP IP = " + WiFi.softAPIP().toString());

    server.on("/", HTTP_GET, []() {
      server.send(200, "text/plain", "Truy cập /update để OTA");
    });

    ElegantOTA.begin(&server, "user", "pass");
    server.begin();
    Serial.println("Ready for OTA at http://" + WiFi.softAPIP().toString() + "/update");
  } 
  // 4) Nếu không thì chạy chế độ bình thường
  else {
    digitalWrite(ledPin, LOW);
    Serial.println("-> Normal mode: OTA disabled");
    // TODO: thêm code ứng dụng chính ở đây
  }
}

void loop() {
  if (otaMode) {
    server.handleClient();
  } else {
    // TODO: xử lý chức năng chính khi không ở OTA mode
  }
}

 

Bài viết liên quan