概要
ESP32 的 OTA(Over-The-Air)升級功能允許通過無線網絡Wi-Fi遠程更新設備固件程序,無需物理連接(如 USB/UART)。比如ESP32設備在機殼內部不好拆卸,人離設備比較遠,不好接線的環境可用到OTA方式給ESP32設備下載程序。為實現此功能每次更新程序的時候都要在代碼里面加入OTA的相關代碼。
創建ESP32-OTA無線局域網網頁版遠程升級入口
打開Arduino IDE中自帶ESP32—OTAWebUpdater示例
#include < WiFi.h >
#include < WiFiClient.h >
#include < WebServer.h >
#include < ESPmDNS.h >
#include < Update.h >
const char* host = "esp32";
const char* ssid = "YXDZ1";
const char* password = "YXDZ#2023#1";
WebServer server(80);
/*
* Login page
*/
const char* loginIndex =
"< form name='loginForm' >"
"< table width='20%' bgcolor='A09F9F' align='center' >"
"< tr >"
"< td colspan=2 >"
"< center >< font size=4 >ESP32 Login Page< /font >< /center >"
"
"
"< /td >"
"
"
"
"
"< /tr >"
"< tr >"
"< td >Username:< /td >"
"< td >< input type='text' size=25 name='userid' >
< /td >"
"< /tr >"
"
"
"
"
"< tr >"
"< td >Password:< /td >"
"< td >< input type='Password' size=25 name='pwd' >
< /td >"
"
"
"
"
"< /tr >"
"< tr >"
"< td >< input type='submit' onclick='check(this.form)' value='Login' >< /td >"
"< /tr >"
"< /table >"
"< /form >"
"< script >"
"function check(form)"
"{"
"if(form.userid.value=='ESP32-OTA' && form.pwd.value=='ESP32-OTA')"
"{"
"window.open('/serverIndex')"
"}"
"else"
"{"
" alert('Error Password or Username')/*displays error message*/"
"}"
"}"
"< /script >";
/*
* Server Index Page
*/
const char* serverIndex =
"< script src='http://www.asorrir.com/images/chaijie_default.png' >< /script >"
"< form method='POST' action='#' enctype='multipart/form-data' id='upload_form' >"
"< input type='file' name='update' >"
"< input type='submit' value='Update' >"
"< /form >"
"progress: 0%"
"< script >"
"$('form').submit(function(e){"
"e.preventDefault();"
"var form = $('#upload_form')[0];"
"var data = new FormData(form);"
" $.ajax({"
"url: '/update',"
"type: 'POST',"
"data: data,"
"contentType: false,"
"processData:false,"
"xhr: function() {"
"var xhr = new window.XMLHttpRequest();"
"xhr.upload.addEventListener('progress', function(evt) {"
"if (evt.lengthComputable) {"
"var per = evt.loaded / evt.total;"
"$('#prg').html('progress: ' + Math.round(per*100) + '%');"
"}"
"}, false);"
"return xhr;"
"},"
"success:function(d, s) {"
"console.log('success!')"
"},"
"error: function (a, b, c) {"
"}"
"});"
"});"
"< /script >";
/*
* setup function
*/
void setup(void) {
Serial.begin(115200);
// Connect to WiFi network
WiFi.begin(ssid, password);
Serial.println("");
// Wait for connection
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.print("Connected to ");
Serial.println(ssid);
Serial.print("IP address: ");
Serial.println(WiFi.localIP());
/*use mdns for host name resolution*/
if (!MDNS.begin(host)) { //http://esp32.local
Serial.println("Error setting up MDNS responder!");
while (1) {
delay(1000);
}
}
Serial.println("mDNS responder started");
/*return index page which is stored in serverIndex */
server.on("/", HTTP_GET, []() {
server.sendHeader("Connection", "close");
server.send(200, "text/html", loginIndex);
});
server.on("/serverIndex", HTTP_GET, []() {
server.sendHeader("Connection", "close");
server.send(200, "text/html", serverIndex);
});
/*handling uploading firmware file */
server.on("/update", HTTP_POST, []() {
server.sendHeader("Connection", "close");
server.send(200, "text/plain", (Update.hasError()) ? "FAIL" : "OK");
ESP.restart();
}, []() {
HTTPUpload& upload = server.upload();
if (upload.status == UPLOAD_FILE_START) {
Serial.printf("Update: %sn", upload.filename.c_str());
if (!Update.begin(UPDATE_SIZE_UNKNOWN)) { //start with max available size
Update.printError(Serial);
}
} else if (upload.status == UPLOAD_FILE_WRITE) {
/* flashing firmware to ESP*/
if (Update.write(upload.buf, upload.currentSize) != upload.currentSize) {
Update.printError(Serial);
}
} else if (upload.status == UPLOAD_FILE_END) {
if (Update.end(true)) { //true to set the size to the current progress
Serial.printf("Update Success: %unRebooting...n", upload.totalSize);
} else {
Update.printError(Serial);
}
}
});
server.begin();
}
void loop(void) {
server.handleClient();
delay(1);
}
并對其中的代碼做如下更改:
給ESP32開發板連接到自己電腦所在的局域網的路由器WIFI上,填上WIFI名稱ssis和密碼password
const char* host = "esp32";
const char* ssid = "YXDZ1";
const char* password = "YXDZ#2023#1";
host為ESP32作為Web服務器時,將ESP32以易記的主機名(如esp32.local)廣播到局域網,其他設備可直接通過該名稱訪問,用戶可通過http://esp32.local直接訪問,無需記憶IP地址
const char* host = "esp32";
/*use mdns for host name resolution*/
if (!MDNS.begin(host)) { //http://esp32.local
Serial.println("Error setting up MDNS responder!");
while (1) {
delay(1000);
}
}
更改好OTA無線局域網網頁版入口的用戶名和密碼,這里都更改為ESP32-OTA
"if(form.userid.value=='ESP32-OTA' && form.pwd.value=='ESP32-OTA')"
通過有線方式連接電腦和ESP32開發板,并把代碼編譯通過先通過有線方式下載到ESP32開發板,讓開發板創建無線OTA遠程升級網頁版入口
打開串口助手,按下ESP32開發板復位,會顯示出所連接的局域網的IP地址,mDNS域名訪問創建成功。
在瀏覽器輸入IP地址或創建的http://esp32.local域名即可跳轉到OTA遠程升級網頁版入口,輸入創建好的用戶名和密碼并登錄
此時再跳轉到程序下載界面,選擇編譯好的程序文件并上傳到開發板內
創建一個ESP32開發板進行OTA升級應用程序示例
若要每次都要對ESP32開發板進行OTA升級,新的應用程序中都要加入上述OTA無線局域網網頁版遠程升級入口的相關代碼。下面為一個ESP32開發板GPIO2引腳上的閃燈程序的代碼,并加入了OTA的相關代碼,然后對OTA部分的代碼進行上述一樣的更改。
#include < WiFi.h >
#include < WiFiClient.h >
#include < WebServer.h >
#include < ESPmDNS.h >
#include < Update.h >
const char* host = "esp32";
const char* ssid = "YXDZ1";
const char* password = "YXDZ#2023#1";
//variabls to blink without delay:
const int led = 2;
unsigned long previousMillis = 0; // will store last time LED was updated
const long interval = 1000; // interval at which to blink (milliseconds)
int ledState = LOW; // ledState used to set the LED
WebServer server(80);
/*
* Login page
*/
const char* loginIndex =
"< form name='loginForm' >"
"< table width='20%' bgcolor='A09F9F' align='center' >"
"< tr >"
"< td colspan=2 >"
"< center >< font size=4 >ESP32 Login Page< /font >< /center >"
"
"
"< /td >"
"
"
"
"
"< /tr >"
"< td >Username:< /td >"
"< td >< input type='text' size=25 name='userid' >
< /td >"
"< /tr >"
"
"
"
"
"< tr >"
"< td >Password:< /td >"
"< td >< input type='Password' size=25 name='pwd' >
< /td >"
"
"
"
"
"< /tr >"
"< tr >"
"< td >< input type='submit' onclick='check(this.form)' value='Login' >< /td >"
"< /tr >"
"< /table >"
"< /form >"
"< script >"
"function check(form)"
"{"
"if(form.userid.value=='ESP32-OTA' && form.pwd.value=='ESP32-OTA')"
"{"
"window.open('/serverIndex')"
"}"
"else"
"{"
" alert('Error Password or Username')/*displays error message*/"
"}"
"}"
"< /script >";
/*
* Server Index Page
*/
const char* serverIndex =
"< script src='http://www.asorrir.com/images/chaijie_default.png' >< /script >"
"< form method='POST' action='#' enctype='multipart/form-data' id='upload_form' >"
"< input type='file' name='update' >"
"< input type='submit' value='Update' >"
"< /form >"
"progress: 0%"
"< script >"
"$('form').submit(function(e){"
"e.preventDefault();"
"var form = $('#upload_form')[0];"
"var data = new FormData(form);"
" $.ajax({"
"url: '/update',"
"type: 'POST',"
"data: data,"
"contentType: false,"
"processData:false,"
"xhr: function() {"
"var xhr = new window.XMLHttpRequest();"
"xhr.upload.addEventListener('progress', function(evt) {"
"if (evt.lengthComputable) {"
"var per = evt.loaded / evt.total;"
"$('#prg').html('progress: ' + Math.round(per*100) + '%');"
"}"
"}, false);"
"return xhr;"
"},"
"success:function(d, s) {"
"console.log('success!')"
"},"
"error: function (a, b, c) {"
"}"
"});"
"});"
"< /script >";
/*
* setup function
*/
void setup(void) {
pinMode(led, OUTPUT);
Serial.begin(115200);
// Connect to WiFi network
WiFi.begin(ssid, password);
Serial.println("");
// Wait for connection
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.print("Connected to ");
Serial.println(ssid);
Serial.print("IP address: ");
Serial.println(WiFi.localIP());
/*use mdns for host name resolution*/
if (!MDNS.begin(host)) { //http://esp32.local
Serial.println("Error setting up MDNS responder!");
while (1) {
delay(1000);
}
}
Serial.println("mDNS responder started");
/*return index page which is stored in serverIndex */
server.on("/", HTTP_GET, []() {
server.sendHeader("Connection", "close");
server.send(200, "text/html", loginIndex);
});
server.on("/serverIndex", HTTP_GET, []() {
server.sendHeader("Connection", "close");
server.send(200, "text/html", serverIndex);
});
/*handling uploading firmware file */
server.on("/update", HTTP_POST, []() {
server.sendHeader("Connection", "close");
server.send(200, "text/plain", (Update.hasError()) ? "FAIL" : "OK");
ESP.restart();
}, []() {
HTTPUpload& upload = server.upload();
if (upload.status == UPLOAD_FILE_START) {
Serial.printf("Update: %sn", upload.filename.c_str());
if (!Update.begin(UPDATE_SIZE_UNKNOWN)) { //start with max available size
Update.printError(Serial);
}
} else if (upload.status == UPLOAD_FILE_WRITE) {
/* flashing firmware to ESP*/
if (Update.write(upload.buf, upload.currentSize) != upload.currentSize) {
Update.printError(Serial);
}
} else if (upload.status == UPLOAD_FILE_END) {
if (Update.end(true)) { //true to set the size to the current progress
Serial.printf("Update Success: %unRebooting...n", upload.totalSize);
} else {
Update.printError(Serial);
}
}
});
server.begin();
}
void loop(void) {
server.handleClient();
delay(1);
//loop to blink without delay
unsigned long currentMillis = millis();
if (currentMillis - previousMillis >= interval) {
// save the last time you blinked the LED
previousMillis = currentMillis;
// if the LED is off turn it on and vice-versa:
ledState = not(ledState);
// set the LED with the ledState of the variable:
digitalWrite(led, ledState);
}
}
ESP32開發板OTA升級下載應用程序
編譯并導出可供OTA升級下載的二進制bin應用程序文件
在項目文件夾下的build文件夾里可看到可供下載的bin應用程序文件
進入OTA無線局域網網頁版遠程升級入口,打開應用程序bin文件,并對ESP32開發板進行遠程下載程序
-
無線局域網
+關注
關注
1文章
240瀏覽量
30415 -
程序
+關注
關注
117文章
3827瀏覽量
83058 -
OTA
+關注
關注
7文章
614瀏覽量
36634 -
ESP32
+關注
關注
21文章
1022瀏覽量
19334
發布評論請先 登錄
GD32單片機STM32遠程下載手機程序升級固件下載局域網網頁升級工具

評論