ESP32非易失性存储整型数据笔记
基于ESP-IDF4.1
1 #include <stdio.h> 2 #include "freertos/FreeRTOS.h" 3 #include "freertos/task.h" 4 #include "esp_system.h" 5 #include "nvs_flash.h" 6 #include "nvs.h" 7 8 void app_main(void) 9 { 10 // 初始化非易失性存储 11 esp_err_t err = nvs_flash_init(); 12 if (err == ESP_ERR_NVS_NO_FREE_PAGES || err == ESP_ERR_NVS_NEW_VERSION_FOUND) { 13 // NVS分区被截断,需要擦除并重新初始化 14 ESP_ERROR_CHECK(nvs_flash_erase()); 15 err = nvs_flash_init(); 16 } 17 ESP_ERROR_CHECK( err ); 18 19 // 打开 20 printf("\n"); 21 printf("Opening Non-Volatile Storage (NVS) handle... "); 22 nvs_handle_t my_handle; 23 err = nvs_open("storage", NVS_READWRITE, &my_handle); 24 if (err != ESP_OK) { 25 printf("Error (%s) opening NVS handle!\n", esp_err_to_name(err)); 26 } else { 27 printf("Done\n"); 28 29 // 读取 30 printf("Reading restart counter from NVS ... "); 31 int32_t restart_counter = 0; // NVC中没有设置值得话,需要设置默认值为0 32 err = nvs_get_i32(my_handle, "restart_counter", &restart_counter); 33 switch (err) { 34 case ESP_OK: 35 printf("Done\n"); 36 printf("Restart counter = %d\n", restart_counter); 37 break; 38 case ESP_ERR_NVS_NOT_FOUND: 39 printf("The value is not initialized yet!\n"); 40 break; 41 default : 42 printf("Error (%s) reading!\n", esp_err_to_name(err)); 43 } 44 45 // 写入 46 printf("Updating restart counter in NVS ... "); 47 restart_counter++; 48 err = nvs_set_i32(my_handle, "restart_counter", restart_counter); 49 printf((err != ESP_OK) ? "Failed!\n" : "Done\n"); 50 51 //提交写入的值,其它时间提交写入没有保证 52 printf("Committing updates in NVS ... "); 53 err = nvs_commit(my_handle); 54 printf((err != ESP_OK) ? "Failed!\n" : "Done\n"); 55 56 // 关闭 57 nvs_close(my_handle); 58 } 59 60 printf("\n"); 61 62 // 设备重启 63 for (int i = 10; i >= 0; i--) { 64 printf("Restarting in %d seconds...\n", i); 65 vTaskDelay(1000 / portTICK_PERIOD_MS); 66 } 67 printf("Restarting now.\n"); 68 fflush(stdout); 69 esp_restart(); 70 }
原文:https://gitee.com/EspressifSystems/esp-idf