Arduino core for ESP32 Wiki content

Preferences library – max key name length

According to the Preferences Example StartCounter.ino the namespace is limited to 15 chars!

This is valid not only for the preferences name, but as well for the preferences keys. For example a key name bluetooth_status will fail while the key name bluetooth_stat works fine.

Example and debug output:

Key name with 16 characters length:

bool bluetooth_status;
Preferences preferences;
preferences.begin("preferences", false);
bluetooth_status =  preferences.getBool("bluetooth_status", false); //NVS key bluetooth status
if (bluetooth_status) {
	Serial.println("bluetooth status: true");
	preferences.putBool("bluetooth_status", false);
} else {
		Serial.println("bluetooth status: false");
		preferences.putBool("bluetooth_status", true);
}
preferences.end();

will fail to write the key value with the following error:

[E][preferences.cpp:306] getUChar(): nvs_get_u8 fail: bluetooth_status NOT_FOUND
bluetooth status: false
[E][preferences.cpp:112] putUChar(): nvs_set_u8 fail: bluetooth_status KEY_TOO_LONG

Changing the length of the key name to 14 characters works fine:

bool bluetooth_status;
Preferences preferences;
preferences.begin("preferences", false);
bluetooth_status =  preferences.getBool("bluetooth_stat", false); //NVS key bluetooth status
if (bluetooth_status) {
	Serial.println("bluetooth status: true");
	preferences.putBool("bluetooth_stat", false);
} else {
		Serial.println("bluetooth status: false");
		preferences.putBool("bluetooth_stat", true);
}
preferences.end();

Debug output after first boot (preference key bluetooth_stat does not exist yet, therefor the first error message):

[E][preferences.cpp:306] getUChar(): nvs_get_u8 fail: bluetooth_stat NOT_FOUND
bluetooth status: false

After a reboot the preferences key is available and true as expected ( no more error message regarding missing key):

bluetooth status: true

And after another reboot the key has the value false:

bluetooth status: false