_____ 使用步骤
1, 初始化 nvs 分区
2, 打开 namespaec
3, 读取或写入键值
如果是 string 或数组类型,先读长度
-- 获取单个数据的值
1, 初始化分区
// Initialize NVS
esp_err_t err = nvs_flash_init();
if (err == ESP_ERR_NVS_NO_FREE_PAGES || err == ESP_ERR_NVS_NEW_VERSION_FOUND) {
// NVS partition was truncated and needs to be erased
// Retry nvs_flash_init
ESP_ERROR_CHECK(nvs_flash_erase());
err = nvs_flash_init();
}
ESP_ERROR_CHECK(err);
2, 打开 namespace, 获得句柄
nvs_handle_t my_handle;
err = nvs_open("binCode", NVS_READWRITE, &my_handle);
如果不是默认分区,用另一个函数
nvs_open_from_partition
3, 读取 key 值
int32_t restart_counter = 0; // value will default to 0, if not set yet in NVS
err = nvs_get_i32(my_handle, "restart_counter", &restart_counter);
4, 设置 key 值
err = nvs_set_i32(my_handle, "restart_counter", restart_counter);
-- 获取数组的值
可以先读数组的长度
然后再读数组的值
获取 string 的值和数组的值类似, nvs_set_str
区别在于 string 类型最后一个字符为 '\0'
esp_err_t err = nvs_flash_init(); printf("Opening Non-Volatile Storage (NVS) handle... ");
nvs_handle_t my_handle;
err = nvs_open("spaceName", NVS_READWRITE, &my_handle);
if (err != ESP_OK) {
printf("Error (%s) opening NVS handle!\n", esp_err_to_name(err));
} else {
printf("Done\n");
// Read run time blob
size_t required_size = 0; // value will default to 0, if not set yet in NVS
// obtain required memory space to store blob being read from NVS
err = nvs_get_blob(my_handle, "datas", NULL, &required_size);
if (err != ESP_OK && err != ESP_ERR_NVS_NOT_FOUND) {
printf("fail, return from nvs_get_blob:\n");
return;
}
printf("Run time:\n");
if (required_size == 0) {
printf("Nothing saved yet!\n");
} else {
uint8_t *testBin = malloc(required_size);
err = nvs_get_blob(my_handle, "datas", testBin, &required_size);
if (err != ESP_OK) {
free(testBin);
return;
}
for (int i = 0; i < required_size / sizeof(uint32_t); i++) {
printf("%d: %d\n", i + 1, testBin[i]);
}
free(testBin);
}
_____ 库文件
#include "nvs_flash.h"
#include "nvs.h"
_____ nvs.h
支持的类型
typedef enum {
NVS_TYPE_U8 = 0x01, /*!< Type uint8_t */
NVS_TYPE_I8 = 0x11, /*!< Type int8_t */