ESP32 OTA升级后断电重启丢失固件重复升级问题求助
问题:ESP32 OTA升级后断电重启丢失固件,重复执行升级流程
通过OTA对ESP32进行固件升级时,设备会自动重启并执行从服务器获取的新程序,但断开电源再重新接通后,设备会再次执行固件升级流程,之前下载的新固件丢失。
代码示例
#include <Arduino.h> #include <WiFi.h> #include <FS.h> #include <SPIFFS.h> #include <esp32fota.h> // esp32fota esp32fota("<Type of Firmware for this device>", <this version>, <validate signature>, <allow insecure https>); esp32FOTA esp32FOTA("esp32-fota-http", 1, false, true); const char* manifest_url = "http://test.technosense.co/fota.json"; void setup_wifi() { delay(10); Serial.print("Connecting to WiFi"); WiFi.begin("wolf","12345678"); while (WiFi.status() != WL_CONNECTED) { delay(500); Serial.print("."); } Serial.println(""); Serial.println(WiFi.localIP()); } void setup() { Serial.begin(115200); esp32FOTA.setManifestURL( manifest_url ); esp32FOTA.printConfig(); setup_wifi(); } void loop() { bool updatedNeeded = esp32FOTA.execHTTPcheck(); if (updatedNeeded) { esp32FOTA.execOTA(); } delay(2000); }
分区情况
使用支持双APP分区的配置,包含factory分区和OTA分区,以及SPIFFS分区,满足OTA升级的基本硬件要求。
使用的库
esp32FOTA库,用于实现HTTP方式的OTA升级功能。
解决方案
检查manifest文件版本配置:确保服务器上的
fota.json中,新版本号大于设备当前固件的版本号(代码中当前版本为1)。若版本号一致,设备每次启动都会触发升级检查并重复执行流程。示例manifest结构:{ "type": "esp32-fota-http", "version": 2, "url": "http://test.technosense.co/new_firmware.bin" }更新新固件的版本号:升级后的新固件代码中,必须将
esp32FOTA初始化时的版本号修改为manifest对应的新版本号(比如2)。如果新固件仍使用版本1,设备重启后会再次判定需要升级。验证分区表正确性:确认使用的是支持OTA的分区表(如
partitions_two_ota.csv),两个APP分区大小一致且足够容纳固件。错误的分区表会导致OTA固件无法被标记为有效启动分区,重启后回到原固件。检查OTA启动状态:添加调试代码确认升级后是否切换到正确的OTA分区:
#include <esp_ota_ops.h> void printCurrentPartition() { const esp_partition_t *running = esp_ota_get_running_partition(); esp_ota_img_states_t ota_state; if (esp_ota_get_state_partition(running, &ota_state) == ESP_OK) { if (ota_state == ESP_OTA_IMG_VALID) { Serial.println("当前运行有效OTA分区"); } else { Serial.println("当前分区未标记为有效"); } } Serial.printf("当前分区类型: %d, 子类型: %d\n", running->type, running->subtype); }在
setup()中调用该函数,查看升级后的分区状态。优化升级检查逻辑:当前代码每2秒执行一次升级检查,建议调整为仅在设备启动时检查一次,或添加开关控制检查时机,避免不必要的重复检测。
内容的提问来源于stack exchange,提问作者Hosein shirani
相关产品推荐
相关产品推荐

