esp32 nvs读写idf完整代码
时间: 2024-05-01 07:19:17 浏览: 152
下面是ESP32 NVS读写的完整代码示例,使用ESP-IDF开发框架:
```
#include <stdio.h>
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "esp_system.h"
#include "nvs_flash.h"
#include "nvs.h"
#define STORAGE_NAMESPACE "storage"
void nvs_write(void)
{
nvs_handle my_handle;
esp_err_t err = nvs_open(STORAGE_NAMESPACE, NVS_READWRITE, &my_handle);
if (err != ESP_OK) {
printf("Error (%s) opening NVS handle!\n", esp_err_to_name(err));
} else {
// Write values including string, binary and integer
uint8_t buf[] = {0x00, 0x01, 0x02, 0x03};
err = nvs_set_i32(my_handle, "int_val", 123);
err = nvs_set_str(my_handle, "string_val", "Hello world");
err = nvs_set_blob(my_handle, "blob_val", buf, sizeof(buf));
printf((err != ESP_OK) ? "Failed to write NVS\n" : "NVS write done\n");
// Close handle
nvs_close(my_handle);
}
}
void nvs_read(void)
{
nvs_handle my_handle;
esp_err_t err = nvs_open(STORAGE_NAMESPACE, NVS_READWRITE, &my_handle);
if (err != ESP_OK) {
printf("Error (%s) opening NVS handle!\n", esp_err_to_name(err));
} else {
// Read values including string, binary and integer
int int_val;
char str_val[20];
size_t size = sizeof(str_val);
uint8_t buf[4];
err = nvs_get_i32(my_handle, "int_val", &int_val);
err = nvs_get_str(my_handle, "string_val", str_val, &size);
err = nvs_get_blob(my_handle, "blob_val", buf, &size);
printf("int_val=%d, string_val=%s, blob_val=%02x%02x%02x%02x\n", int_val, str_val, buf[0], buf[1], buf[2], buf[3]);
// Close handle
nvs_close(my_handle);
}
}
void app_main()
{
// Initialize NVS
esp_err_t err = nvs_flash_init();
if (err == ESP_ERR_NVS_NO_FREE_PAGES || err == ESP_ERR_NVS_NEW_VERSION_FOUND) {
// NVS partition was truncated and needs to be erased
printf("NVS partition was truncated and needs to be erased\n");
err = nvs_flash_erase();
if (err != ESP_OK) {
printf("Failed to erase NVS partition (%s)\n", esp_err_to_name(err));
return;
}
// Retry nvs_flash_init
err = nvs_flash_init();
}
if (err != ESP_OK) {
printf("Failed to initialize NVS (%s)\n", esp_err_to_name(err));
return;
}
// Write and read NVS values
nvs_write();
nvs_read();
}
```
此代码在ESP32上使用NVS Flash存储写入和读取值,并使用ESP-IDF开发框架进行编写。在使用此代码之前,应该先在ESP32上执行`nvs_flash_init()`进行初始化。
阅读全文