Preferences is the Arduino wrapper around ESP-IDF's NVS (non-volatile storage). Data lives in the nvs flash partition and survives restarts, deep sleep and power loss.
Limits that bite
| Limit | Value |
|---|---|
| Namespace and key length | 15 characters max (ASCII) |
| String value | 4000 bytes including the terminator |
| Best use | many small values (settings, counters, calibration) |
| Not for | logs, large files, frequently rewritten big blobs → use a file system such as LittleFS |
Keys longer than 15 characters fail; this is a frequent reason for "settings are not saved".
Pattern
#include <Preferences.h>
Preferences prefs;
struct Config {
String ssid;
uint32_t intervalSec;
};
Config loadConfig() {
Config c;
prefs.begin("app", true); // read-only: writes would fail
c.ssid = prefs.getString("wifi_ssid", "");
c.intervalSec = prefs.getUInt("interval_s", 300); // default if missing
prefs.end();
return c;
}
void saveInterval(uint32_t seconds) {
prefs.begin("app", false); // read-write
if (prefs.getUInt("interval_s", 0) != seconds) { // don't rewrite unchanged values
prefs.putUInt("interval_s", seconds);
}
prefs.end();
}
Tips
- Always pass a default to
get*()so a fresh or erased device boots with sane values. - Skip unchanged writes. NVS spreads writes across the partition, but flash still wears; don't write a value on every loop iteration.
- Version your schema: store a
cfg_verkey and migrate old layouts on boot. - Credentials: NVS is not encrypted unless you enable NVS encryption (ESP-IDF feature). Anyone with the flash contents can read plain NVS.
- Erasing flash (
esptool erase_flash) also erases NVS.