Hướng dẫn sử dụng OTA (Over-The-Air) cho ESP32
OTA (Over-The-Air) cho phép bạn update firmware ESP32 qua WiFi mà không cần cắm cáp USB. Đây là tính năng cực kỳ quan trọng khi deploy thiết bị IoT ngoài thực tế.
1. OTA là gì?
OTA là cơ chế giúp ESP32:
- Nhận firmware mới qua mạng (WiFi)
- Ghi firmware vào flash
- Tự reboot và chạy phiên bản mới
👉 Không cần tháo thiết bị hay cắm dây lại
2. Chuẩn bị
Phần cứng
- ESP32 (NodeMCU-32S, DevKit V1,...)
- WiFi
Phần mềm
- Arduino IDE hoặc PlatformIO
- Thư viện:
- WiFi.h
- ArduinoOTA.h
3. Code OTA cơ bản
#include <WiFi.h> #include <ArduinoOTA.h> const char* ssid = "YOUR_WIFI"; const char* password = "YOUR_PASSWORD"; void setup() { Serial.begin(115200); WiFi.begin(ssid, password); while (WiFi.waitForConnectResult() != WL_CONNECTED) { Serial.println("WiFi Failed! Rebooting..."); delay(5000); ESP.restart(); } // OTA setup ArduinoOTA.setHostname("esp32-ota"); ArduinoOTA.onStart([]() { Serial.println("Start updating..."); }); ArduinoOTA.onEnd([]() { Serial.println("\nEnd"); }); ArduinoOTA.onProgress([](unsigned int progress, unsigned int total) { Serial.printf("Progress: %u%%\r", (progress / (total / 100))); }); ArduinoOTA.onError([](ota_error_t error) { Serial.printf("Error[%u]: ", error); }); ArduinoOTA.begin(); Serial.println("Ready"); Serial.print("IP address: "); Serial.println(WiFi.localIP()); } void loop() { ArduinoOTA.handle(); }