在ESP32设备上更新固件时,如果需要保留设备配置,可以采取以下几种方法:
1. 使用NVS(Non-Volatile Storage)
ESP32提供了NVS,用于存储小量的非易失性数据。你可以在更新固件之前,将设备配置保存在NVS中,更新完成后再读取这些配置。
保存配置到NVS:
#include "nvs_flash.h"
#include "nvs.h"
// 初始化NVS
esp_err_t ret = nvs_flash_init();
if (ret == ESP_ERR_NVS_NO_FREE_PAGES || ret == ESP_ERR_NVS_NEW_VERSION_FOUND) {
ESP_ERROR_CHECK(nvs_flash_erase());
ret = nvs_flash_init();
}
ESP_ERROR_CHECK(ret);
// 保存配置
nvs_handle_t my_handle;
ret = nvs_open("storage", NVS_READWRITE, &my_handle);
ESP_ERROR_CHECK(ret);
int32_t my_config = 12345; // 示例配置数据
ret = nvs_set_i32(my_handle, "config_key", my_config);
ESP_ERROR_CHECK(ret);
ret = nvs_commit(my_handle);
ESP_ERROR_CHECK(ret);
nvs_close(my_handle);
读取配置从NVS:
int32_t my_config = 0;
ret = nvs_open("storage", NVS_READONLY, &my_handle);
ESP_ERROR_CHECK(ret);
ret = nvs_get_i32(my_handle, "config_key", &my_config);
switch (ret) {
case ESP_OK:
printf("Configuration loaded: %d\n", my_config);
break;
case ESP_ERR_NVS_NOT_FOUND:
printf("The value is not initialized yet!\n");
break;
default :
ESP_ERROR_CHECK(ret);
}
nvs_close(my_handle);
2. 使用SPIFFS或FAT文件系统
你可以使用SPIFFS或FAT文件系统在ESP32的Flash中存储配置文件。这样在固件更新后,配置文件仍然存在,可以继续使用。
初始化SPIFFS:
#include "esp_spiffs.h"
esp_vfs_spiffs_conf_t conf = {
.base_path = "/spiffs",
.partition_label = NULL,
.max_files = 5,
.format_if_mount_failed = true
};
esp_err_t ret = esp_vfs_spiffs_register(&conf);
if (ret != ESP_OK) {
if (ret == ESP_FAIL) {
printf("Failed to mount or format filesystem\n");
} else if (ret == ESP_ERR_NOT_FOUND) {
printf("Failed to find SPIFFS partition\n");
} else {
printf("Failed to initialize SPIFFS (%s)\n", esp_err_to_name(ret));
}
return;
}
保存配置到文件:
FILE* f = fopen("/spiffs/config.txt", "w");
if (f == NULL) {
printf("Failed to open file for writing\n");
return;
}
fprintf(f, "my_config_value: %d\n", my_config);
fclose(f);
读取配置从文件:
FILE* f = fopen("/spiffs/config.txt", "r");
if (f == NULL) {
printf("Failed to open file for reading\n");
return;
}
char line[64];
fgets(line, sizeof(line), f);
printf("Read from file: '%s'\n", line);
fclose(f);
3. 通过OTA更新保留数据分区
在使用OTA(Over-The-Air)更新时,可以配置固件分区表,使配置数据存储在一个独立的分区,从而在更新固件时不影响这个分区。
阅读全文
公众号近期文章
赞赏支持
0 Responses to “Esp32更新固件如何保留设备配置”