不存在nvs_get_key 这个函数
时间: 2024-03-09 20:44:57 浏览: 71
非常抱歉,我犯了一个错误。ESP-IDF 中确实没有 nvs_get_key 函数。正确的方法是使用 nvs_flash_read 函数读取 NVS 分区的内容,然后遍历键值对来获取所有键。
以下是一个示例代码:
```c
#include "nvs_flash.h"
// 读取 NVS 分区的内容并打印所有键
void print_nvs_keys() {
esp_err_t err = nvs_flash_init();
if (err != ESP_OK) {
printf("Error initializing NVS flash: %s\n", esp_err_to_name(err));
return;
}
nvs_handle_t nvs_handle;
err = nvs_open("my_namespace", NVS_READONLY, &nvs_handle);
if (err != ESP_OK) {
printf("Error opening NVS handle: %s\n", esp_err_to_name(err));
return;
}
size_t required_size;
err = nvs_flash_read(NULL, &required_size);
if (err != ESP_OK && err != ESP_ERR_NVS_NOT_FOUND) {
printf("Error reading NVS partition size: %s\n", esp_err_to_name(err));
return;
}
uint8_t* buffer = malloc(required_size);
if (buffer == NULL) {
printf("Error allocating memory for NVS partition!\n");
return;
}
err = nvs_flash_read(buffer, &required_size);
if (err != ESP_OK) {
printf("Error reading NVS partition: %s\n", esp_err_to_name(err));
free(buffer);
return;
}
nvs_iterator_t it = nvs_entry_find_start(nvs_handle);
while (it != NULL) {
nvs_entry_info_t info;
err = nvs_entry_info(it, &info);
if (err != ESP_OK) {
printf("Error getting NVS entry info: %s\n", esp_err_to_name(err));
break;
}
printf("NVS key: %s\n", info.key);
it = nvs_entry_find_next(it);
}
nvs_entry_find_end(it);
nvs_close(nvs_handle);
free(buffer);
}
```
该示例代码首先初始化 NVS 分区,然后打开一个名为 "my_namespace" 的只读 NVS 命名空间。接下来,它使用 nvs_flash_read 函数读取 NVS 分区的内容,并遍历键值对来获取所有键。最后,它关闭 NVS 命名空间句柄和释放分配的内存。
请注意,该示例代码假设你已经正确地配置了 NVS 分区。如果你还没有配置 NVS 分区,请参考 Espressif 官方文档中关于 NVS 的部分。
阅读全文
相关推荐


















