An ESP32 usually needs to remember a few choices after a reboot. A sampling interval, selected operating mode, or calibration offset belongs in persistent storage. A sensor reading taken every second generally does not. Arduino-ESP32’s Preferences library stores small, named values in the ESP32’s non-volatile storage (NVS) and is a practical choice for settings that change infrequently.
Start with a default and validate what you read
Put related settings in a short namespace. The examples below use settings for the namespace and sample_ms for the key. Both names fit NVS’s 15-character limit. Open the namespace read-only during startup and supply a default when the namespace or key does not exist. Validate the result again before applying it. A value saved by older firmware could be outside the range the current build supports. Espressif Arduino-ESP32 Preferences API
Save only when the user changes a setting
Keep the working value in RAM. When the user turns a knob or presses a button repeatedly, update RAM immediately and wait for a short quiet period before saving the final value. If the user changes the value and then changes it back, compare with the last saved value and skip the write.
This illustrative Arduino sketch uses two serial commands so you can try the pattern without extra hardware. Send 1 for a one-second sampling interval or 2 for two seconds. The sketch records the final choice after 1.5 seconds of inactivity. It prints the setting and does not implement a sensor loop.
#include <Arduino.h>
#include <Preferences.h>
constexpr char settingsNamespace[] = "settings";
constexpr char intervalKey[] = "sample_ms";
constexpr uint32_t defaultMs = 1000;
constexpr uint32_t quietMs = 1500;
uint32_t activeMs = defaultMs;
uint32_t savedMs = defaultMs;
uint32_t changedAt = 0;
uint32_t loadInterval() {
Preferences settings;
if (!settings.begin(settingsNamespace, true)) return defaultMs;
const uint32_t stored = settings.getUInt(intervalKey, defaultMs);
settings.end();
return stored == 1000 || stored == 2000 ? stored : defaultMs;
}
bool saveInterval(uint32_t value) {
Preferences settings;
if (!settings.begin(settingsNamespace, false)) return false;
const size_t written = settings.putUInt(intervalKey, value);
settings.end();
return written == sizeof(value);
}
void setup() {
Serial.begin(115200);
activeMs = savedMs = loadInterval();
Serial.printf("Starting interval: %lu ms\n", (unsigned long)activeMs);
Serial.println("Send 1 or 2 to change the interval.");
}
void loop() {
const int command = Serial.read();
if (command == '1' || command == '2') {
const uint32_t next = command == '1' ? 1000 : 2000;
if (next != activeMs) {
activeMs = next;
changedAt = millis();
Serial.printf("Active interval: %lu ms\n", (unsigned long)activeMs);
}
}
const uint32_t now = millis();
if (activeMs != savedMs && uint32_t(now - changedAt) >= quietMs) {
changedAt = now;
if (saveInterval(activeMs)) {
savedMs = activeMs;
Serial.println("Saved interval");
} else {
Serial.println("Save failed. Still using the setting in RAM.");
}
}
delay(1);
}
Preferences reports how many bytes a putUInt() succeeds in writing. Update the last-saved value only after that result confirms success. If saving fails, your UI can show the active setting and a separate persistence error. Projects with limited foreground latency should measure the save call and arrange flash operations outside time-sensitive work.
Pick a different store for frequent or grouped writes
NVS is designed around flash-backed key-value storage and distributes its writes, but flash still has finite erase endurance. Avoid treating a Settings menu as a datalogger. Keep live counters in RAM when loss at restart is acceptable, checkpoint them at a defined interval when you must preserve progress, and design continuous logging around the expected write volume and lifetime. Espressif file-system and flash endurance guidance
When several settings must change together, avoid assuming that separate put calls form one atomic update. Consider one versioned record with explicit fields, length checking and a recovery policy. Preferences is most useful for small records. Espressif recommends a filesystem for larger bodies of data. Espressif Preferences tutorial
Test the behaviour you intend to ship
- Start with a fresh namespace. The sketch should print the default interval.
- Send several alternating commands quickly. Wait for one save message, reboot, and confirm that the last value persisted.
- Choose a different value and return to the saved value before the quiet period ends. Check that no new save message appears.
- Reset immediately after a change and then repeat after waiting for the save message. The difference is the period in which the new value lives only in RAM.
If a product promises that an operator’s configuration is durable immediately, an explicit Save button with a confirmed result may be a better fit than automatic debouncing. Choose the delay and failure feedback to match what the operator needs to know before cycling power.
