avatar

松果工作室

欢迎光临

  • 首页
  • freeRTOS
  • ESP
  • 开发手册
  • 快速笔记
  • 个人收藏
  • 工具
Home ESP32(七) NVS
文章

ESP32(七) NVS

Posted 2025-03-18 Updated 2025-03- 18
By YCP
5~7 min read

基本概念

  • 命名空间(Namespace)​:NVS 数据按命名空间分组,避免键名冲突。
  • 键值对(Key-Value)​:支持存储整数、字符串、二进制数据等类型。
  • 存储限制:每个键值对最大 1984KB,单个命名空间总大小取决于分区表配置(默认约 24KB)。

示例代码

#include <stdio.h>
#include "nvs_flash.h"
#include "esp_system.h"

void nvs_demo() {
    // 初始化 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 handle;
    ESP_ERROR_CHECK(nvs_open("my_storage", NVS_READWRITE, &handle));

    // 写入数据,键值对
    ESP_ERROR_CHECK(nvs_set_i32(handle, "boot_count", 100));
    ESP_ERROR_CHECK(nvs_set_str(handle, "device_id", "ESP32_1234"));

    // 读取数据
    int32_t boot_count = 0;
    ESP_ERROR_CHECK(nvs_get_i32(handle, "boot_count", &boot_count));
    printf("Boot count: %d\n", boot_count);

    // 获取存入的字符串,要先获取长度,再获取具体字符串
    size_t id_len;
    ESP_ERROR_CHECK(nvs_get_str(handle, "device_id", NULL, &id_len));
    char *id = malloc(id_len);
    ESP_ERROR_CHECK(nvs_get_str(handle, "device_id", id, &id_len));
    printf("Device ID: %s\n", id);
    free(id);

    // 关闭
    nvs_close(handle);
}
ESP
License:  CC BY 4.0
Share

Further Reading

OLDER

ESP32(四) STA & AP

NEWER

ESP32(八) 简单的webserver

Recently Updated

  • ESP32(八) 简单的webserver
  • ESP32(七) NVS
  • ESP32(四) STA & AP
  • 多级菜单
  • ESP32(五) ESP32 OTA

Trending Tags

WCH Linux Elec freeRTOS STM ESP Flutter Others SwiftUI

Contents

©2025 松果工作室. Some rights reserved.

Using the Halo theme Chirpy