esp32s3 NVS空间读写操作
esp32s3 NVS空间读写操作
非易失性存储 (NVS) 库主要用于在 flash 中存储键值格式的数据。官网介绍
我简单理解就是存放一些简单的键值对。比如账号、密码之类的简单字符。用“键”来访问,反馈回来值。
demo参考示例写的,比较简单,补充如下。
#include <stdio.h>
#include "nvs_flash.h"
#include "esp_err.h"
#include "esp_log.h"
#include <string.h>
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#define NAME_SPACE_WIFI1 "wifi1"
#define NAME_SPACE_WIFI2 "wifi2"
#define NVS_SSID_KEY "ssid"
#define NVS_PASSWORD_KEY "password"
/*namespace:命名空间
key:
buf:内存地址
maxlen:最大读取长度
*/
void nvs_blob_read(const char *namespace,const char *key,void *buf,int maxlen)
{
nvs_handle_t nvs_handle;
size_t length = 0;
nvs_open(namespace,NVS_READONLY,&nvs_handle);
nvs_get_blob(nvs_handle,key,NULL,&length); //outvalue参数为NULL,则只返回数据长度
if(length>0 && length<maxlen)
{
nvs_get_blob(nvs_handle,key,buf,&length); //outvalue参数为NULL,则只返回数据长度
}
nvs_close(nvs_handle);
}
void app_main(void)
{
nvs_handle_t nvs_handle1;
nvs_handle_t nvs_handle2;
esp_err_t ret = nvs_flash_init();
if(ret != ESP_OK)
{
nvs_flash_erase();
ESP_ERROR_CHECK(nvs_flash_init());
}
/*命名空间1操作 nvs写入*/
nvs_open(NAME_SPACE_WIFI1,NVS_READWRITE,&nvs_handle1);
nvs_set_blob(nvs_handle1,NVS_SSID_KEY,"mywifi_esp32",strlen("mywifi_esp32"));
nvs_set_blob(nvs_handle1,NVS_PASSWORD_KEY,"12345678",strlen("12345678"));
nvs_commit(nvs_handle1); //立即写入nvs
nvs_close(nvs_handle1);
/*命名空间2操作 nvs写入 */
nvs_open(NAME_SPACE_WIFI2,NVS_READWRITE,&nvs_handle2);
nvs_set_blob(nvs_handle2,NVS_SSID_KEY,"helloworld",strlen("helloworld"));
nvs_set_blob(nvs_handle2,NVS_PASSWORD_KEY,"87654321",strlen("87654321"));
nvs_commit(nvs_handle2); //立即写入nvs
nvs_close(nvs_handle2);
vTaskDelay(pdMS_TO_TICKS(1000));
/*nvs读取*/
char read_buffer[64];
/*命名空间1中的键值对读取*/
memset(read_buffer,0,sizeof(read_buffer));
nvs_blob_read(NAME_SPACE_WIFI1,NVS_SSID_KEY,read_buffer,sizeof(read_buffer));
ESP_LOGI("nvs","namespace:%s,key:%s -> value:%s",NAME_SPACE_WIFI1,NVS_SSID_KEY,read_buffer);
memset(read_buffer,0,sizeof(read_buffer));
nvs_blob_read(NAME_SPACE_WIFI1,NVS_PASSWORD_KEY,read_buffer,sizeof(read_buffer));
ESP_LOGI("nvs","namespace:%s,key:%s -> value:%s",NAME_SPACE_WIFI1,NVS_PASSWORD_KEY,read_buffer);
/*命名空间2中的键值对读取*/
memset(read_buffer,0,sizeof(read_buffer));
nvs_blob_read(NAME_SPACE_WIFI2,NVS_SSID_KEY,read_buffer,sizeof(read_buffer));
ESP_LOGI("nvs","namespace:%s,key:%s -> value:%s",NAME_SPACE_WIFI2,NVS_SSID_KEY,read_buffer);
memset(read_buffer,0,sizeof(read_buffer));
nvs_blob_read(NAME_SPACE_WIFI2,NVS_PASSWORD_KEY,read_buffer,sizeof(read_buffer));
ESP_LOGI("nvs","namespace:%s,key:%s -> value:%s",NAME_SPACE_WIFI2,NVS_PASSWORD_KEY,read_buffer);
/*nvs读取*/
// size_t length = 0;
// nvs_open(NAME_SPACE_WIFI1,NVS_READONLY,&nvs_handle1);
// nvs_get_blob(nvs_handle1,NVS_SSID_KEY,NULL,&length); //outvalue参数为NULL,则只返回数据长度
// if(length>0)
// {
// char* buffer = (char*)malloc(length + 1);
// nvs_get_blob(nvs_handle1,NVS_SSID_KEY,buffer,&length); //outvalue参数为NULL,则只返回数据长度
// }
}