nvs_store.c
The NVS partition is ESP-IDF's survival memory: radio pairs, Wi-Fi keys, Matter IDs live there as key-value pairs with wear leveling. This sketch persists a boot counter and reads a string.
Hardware required
An ESP32-H2 board (RISC-V 96 MHz, IEEE 802.15.4 radio only — no Wi-Fi) such as a DevKitM-1, powered over USB. None: the module flash suffices (nvs partition created by idf.py).
Wiring
No wiring. USB-Serial/JTAG console to watch the logs at each reboot.
How it works
nvs_flash_init mounts the partition (auto-erase when blank), nvs_open opens the « config » namespace, set_i32+commit guarantee the write. nvs_get_str takes NULL for size and returns ESP_ERR_NVS_NOT_FOUND when missing. Program it with ESP-IDF (idf.py set-target esp32h2); the USB-Serial/JTAG port (GPIO26/27) acts as console and flash port. Hold Boot + Reset for download mode if needed.
Going further
Store your node settings (802.15.4 channel, sensor thresholds) there and add a factory-reset via nvs_flash_erase().
nvs_store.c
// nvs_store.c — compteur persistant dans la partition NVS.
#include <string.h>
#include "nvs_flash.h"
#include "nvs.h"
#include "esp_log.h"
static const char *TAG = "nvs";
void app_main(void)
{
esp_err_t err = nvs_flash_init(); // partition « nvs » du partition table
if (err == ESP_ERR_NVS_NO_FREE_PAGES || err == ESP_ERR_NVS_NEW_VERSION_FOUND) {
ESP_ERROR_CHECK(nvs_flash_erase()); // efface seulement au 1er flash
err = nvs_flash_init();
}
ESP_ERROR_CHECK(err);
nvs_handle_t h;
ESP_ERROR_CHECK(nvs_open("config", NVS_READWRITE, &h));
int32_t n = 0;
nvs_get_i32(h, "compteur", &n); // 0 si absent
n++;
ESP_ERROR_CHECK(nvs_set_i32(h, "compteur", n));
ESP_ERROR_CHECK(nvs_commit(h)); // ecriture physique
ESP_LOGI(TAG, "demarrage n°%d persiste", (int)n);
char wifi[32] = "inconnu";
if (nvs_get_str(h, "reseau", wifi, NULL) == ESP_OK)
ESP_LOGI(TAG, "reseau memorise : %s", wifi);
nvs_close(h);
while (1) vTaskDelay(pdMS_TO_TICKS(1000));
}