Chapter 7: NVS Parameter Persistence
7.1 Key Points
- ESP-IDF NVS Flash concepts: namespace, key, and value
- Storing and loading PID parameters
- Default values when NVS data is missing
- Updating parameters without recompiling firmware
7.2 Course Content
NVS stores small key-value data in flash. In the OSRCORE examples, it is used for PID parameters and other runtime settings. After tuning parameters through a serial interface or debug command, the values can be saved and restored after reboot.
7.3 Basic Learning
NVS Concepts
NVS organizes data by namespace. Each namespace contains keys. Values can be integers, strings, binary blobs, or floating-point values stored as raw bytes.
Common steps:
- Initialize NVS flash.
- Open a namespace.
- Read or write values.
- Commit writes.
- Close the handle.
Typical PID Parameter Set
| Parameter | Meaning |
|---|---|
kp | Proportional gain |
ki | Integral gain |
kd | Derivative gain |
target_speed | Desired speed |
7.4 Program Study
Initialize NVS:
c
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());
ESP_ERROR_CHECK(nvs_flash_init());
}Open a namespace and read parameters:
c
nvs_handle_t handle;
ESP_ERROR_CHECK(nvs_open("pid", NVS_READWRITE, &handle));
size_t len = sizeof(pid_params_t);
esp_err_t err = nvs_get_blob(handle, "params", ¶ms, &len);
if (err == ESP_ERR_NVS_NOT_FOUND) {
params.kp = 1.0f;
params.ki = 0.0f;
params.kd = 0.0f;
}Write and commit parameters:
c
ESP_ERROR_CHECK(nvs_set_blob(handle, "params", ¶ms, sizeof(params)));
ESP_ERROR_CHECK(nvs_commit(handle));
nvs_close(handle);7.5 Summary
NVS makes runtime tuning practical. Instead of hard-coding PID parameters, the firmware can store tuned values in flash and load them automatically after each reboot.