107-ESP32_SDK開發-flash數據存儲nvs


<p><iframe name="ifd" src="https://mnifdv.cn/resource/cnblogs/LearnESP32" frameborder="0" scrolling="auto" width="100%" height="1500"></iframe></p>

 

說明

nvs是底層封裝的一套把數據存儲到flash里面的函數;

數據是以鍵值對的形式存儲數據(就是標識符+數據的形式)

 

不如直接看代碼

 

#include <stdio.h>
#include <string.h>
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "freertos/queue.h"
#include "freertos/event_groups.h"
#include "esp_system.h"
#include "nvs_flash.h"
#include "esp_log.h"


void app_main(void)
{
    //初始化 NVS
    esp_err_t err = nvs_flash_init();
    if (err == ESP_ERR_NVS_NO_FREE_PAGES || err == ESP_ERR_NVS_NEW_VERSION_FOUND) {
      ESP_ERROR_CHECK(nvs_flash_erase());
      err = nvs_flash_init();
    }
    ESP_ERROR_CHECK(err);


    /*操作nvs時用的句柄*/
    nvs_handle_t my_handle;

    /*打開*/     //操作的表格名字 //以讀寫模式打開
    err = nvs_open("storage", NVS_READWRITE, &my_handle);

    /**/
    err = nvs_set_i32(my_handle, "test", 111);
    /*提交*/
    err = nvs_commit(my_handle);

    int32_t test_value;
    /**/
    err = nvs_get_i32(my_handle, "test", &test_value);
    printf("test_value = %d\n", test_value);

    /*關閉*/
    nvs_close(my_handle);
}

 

1.其實相當於操作一個表格,初始化和打開這個表格

storage代表做操作的表格的名字,可隨意設置,字符串的長度默認最長15個字符 (NVS_PART_NAME_MAX_SIZE - 1)

 

 

 

2.設置表格中字段名字為test的值為111 

 

 

i32代表32字節數據,其實有許多類型

 

 

test字符串是咱的數據的標簽名在數據庫中也常叫做字段名

,可隨意設置,字符串的長度默認最長15個字符 (NVS_PART_NAME_MAX_SIZE - 1)

 

后面的111是設置的值

 

 

3.提交

設置完值以后調用一下提交函數

 

 

 

4.讀取

 

 

 

更加詳細的代碼可參看官方

 

 

 

 

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM