Persistent Data Storage on ESP32: Leveraging EEPROM and Preferences for Permanent Data Retention

In ESP32, you have the ability to programmatically read and write data into the flash memory, similar to using a USB flash drive. This storage partition within the flash memory is known as Non-volatile Storage (NVS), which is specifically designed to store key-value pairs of data. While both the EEPROM and Preferences libraries can be used to store data in NVS, the EEPROM library is primarily intended for compatibility with Arduino code. However, it may not offer optimal performance. Therefore, it is highly recommended to use the Preferences library instead of the EEPROM library for improved performance.

It's important to note that by default, the Non-volatile Storage (NVS) on ESP32 is not encrypted, and all data is stored in plain text. If you plan to store sensitive data in the NVS, it's crucial to consider encrypting the NVS partition. However, in the Arduino IDE, there is currently no straightforward method to encrypt the NVS. To encrypt the NVS, you would need to utilize the terminal with Espressif toolkits or other relevant tools to accomplish this task.

In this example, I will demonstrate how to utilize the preferences feature in order to track the boot time of an ESP32. Each time the ESP32 boots up, it will retrieve the current counter value from the Non-volatile Storage (NVS), increment it by 1, save the updated value back to NVS, and proceed with the reboot. By employing this approach, the boot time can be permanently stored for future reference.

preferences.begin("lonelybinary", false);

Open the namespace "lonelybinary" with RW permission.
"lonelybinary" is the namespace.
false means Read and Write,
true means Read Only

preferences.getInt("counter", 0) Read the key "counter" 's value, in namespace "lonelybinary". If "counter" doesn't exist, return the default value "0".
preferences.putInt("counter", 100) Save the key "counter" value 100 in namespace "lonelybinary"
preferences.clear() Clear all keys in "lonelybinary" namespace
preferences.remove("counter") Clear key "counter" in "lonelybinary" namespace
preferences.isKey("counter") Is key "counter" exist in "lonelybinary" namespace ?
Serial.println(preferences.isKey("counter") ? "Yes" : "No");
preferences.getType("counter")
return key "counter" type
preferences.end() Close the namespace

 

Data Type Read Write
Char putChar getChar
Unsigned Char putUChar getUChar
Short putShort getShort
Unsigned Short putUShort getUShort
Int putInt getInt
Unsigned Int putUint getUint
Long putLong getLong
Unsigned Long putUlong getUlong
Long64 putLong64 getLong64
Unsigned Long64 putUlong64 getUlong64
Float putFloat getFloat
Double putDouble getDouble
Bool putBool getBool
String putString getString
Bytes putBytes getBytes

 

RELATED ARTICLES

Leave a comment

Your email address will not be published. Required fields are marked *

Please note, comments must be approved before they are published