一、概述
非易失性存储 (NVS) 库主要用于在 flash 中存储键值格式的数据。本文档将详细介绍 NVS 在ESP32中的使用。
NVS 的操作对象为键值对,其中键是 ASCII 字符串,当前支持最大键长为 15 个字符,值可以为以下几种类型:
- 整数型:
uint8_t
、int8_t
、uint16_t
、int16_t
、uint32_t
、int32_t
、uint64_t
和int64_t
; - 字符型:以
\0
结尾的字符串; - 二进制数据:可变长度的二进制数据 (BLOB)。
二、NVS初始化
#include "nvs_flash.h"
void main(void)
{
...
ESP_ERROR_CHECK(nvs_flash_init());
...
}
三、NVS写
/******************************************
* PUBLIC FUNCTIONS
*/
/**
@brief 数据写入Flash
@param 无
@return 无
*/
void NvsWriteDataToFlash(void)
{
nvs_handle handle;
// 写入一个整形数据,一个字符串,WIFI信息以及版本信息
static const char *NVS_CUSTOMER = "customer data";
static const char *DATA1 = "Integer";
static const char *DATA2 = "String";
static const char *DATA3 = "blob_wifi";
static const char *DATA4 = "blob_version";
// 要写入的整型数据
int32_t value_for_store = 666;
// 要写入的字符串
char str_for_store[32] = "i am a string.";
// 要写入的WIFI信息
wifi_config_t wifi_config_to_store = {
.sta = {
.ssid = "store_ssid:hello_kitty",
.password = "store_password:1234567890",
},
};
// 要写入的版本号
uint8_t version_for_store[4] = {0x01, 0x01, 0x01, 0x00};
printf("set size:%u\r\n", sizeof(wifi_config_to_store));
ESP_ERROR_CHECK( nvs_open( NVS_CUSTOMER, NVS_READWRITE, &handle) );
ESP_ERROR_CHECK( nvs_set_i32( handle, DATA1, value_for_store) );
ESP_ERROR_CHECK( nvs_set_str( handle, DATA2, str_for_store) );
ESP_ERROR_CHECK( nvs_set_blob( handle, DATA3, &wifi_config_to_store, sizeof(wifi_config_to_store)) );
ESP_ERROR_CHECK( nvs_set_blob( handle, DATA4, version_for_store, 4) );
ESP_ERROR_CHECK( nvs_commit(handle) );
nvs_close(handle);
}
四、NVS读
/**
@brief 读取Flash数据
@param 无
@return 无
*/
void NvsReadDataFromFlash(void)
{
esp_err_t err;
nvs_handle handle;
static const char *NVS_CUSTOMER = "customer data";
static const char *DATA1 = "Integer";
static const char *DATA2 = "String";
static const char *DATA3 = "blob_wifi";
static const char *DATA4 = "blob_version";
uint32_t str_length = 32;
char str_data[32] = {0};
int32_t value = 0;
wifi_config_t wifi_config_stored;
uint8_t version[4] = {0};
uint32_t version_len = 4;
memset(&wifi_config_stored, 0x0, sizeof(wifi_config_stored));
uint32_t wifi_len = sizeof(wifi_config_stored);
ESP_ERROR_CHECK( nvs_open(NVS_CUSTOMER, NVS_READWRITE, &handle) );
ESP_ERROR_CHECK ( nvs_get_i32(handle, DATA1, &value) );
ESP_ERROR_CHECK ( nvs_get_str(handle, DATA2, str_data, &str_length) );
ESP_ERROR_CHECK ( nvs_get_blob(handle, DATA3, &wifi_config_stored, &wifi_len) );
ESP_ERROR_CHECK ( nvs_get_blob(handle, DATA4, version, &version_len) );
printf("[data1]: %s len:%u\r\n", str_data, str_length);
printf("[data2]: %d\r\n", value);
printf("[data3]: ssid:%s passwd:%s\r\n", wifi_config_stored.sta.ssid, wifi_config_stored.sta.password);
nvs_close(handle);
}
• 由 青梅煮久 写于 2020 年 12 月 19 日
• 参考:
https://docs.espressif.com/projects/esp-idf/zh_CN/latest/esp32/api-reference/storage/nvs_flash.html
https://blog.csdn.net/espressif/article/details/84749096