IoT/ESP32 B.Tech/Diploma Beginner

ESP32 Save Data Permanently using Preferences Library

Save data permanently on the ESP32 flash memory using Preferences.h library. The data held in the flash memory persists across resets or power failures. Save credentials, API keys, threshold values

  • Suitable forB.Tech/Diploma IoT/ESP32 students
  • Build time1-2 weeks
  • LevelBeginner
  • Available atAjvika Labs, Kakinada

About this project

This guide shows how to save data permanently on the ESP32 flash memory using the
Preferences.h
library. The data held in the flash memory persists across resets or power failures. Using the
Preferences.h
library is useful to save data like network credentials, API keys, threshold values, or even the last state of a GPIO. You’ll learn how to save and read data from flash memory.
In this tutorial, we’ll cover the following topics:
Save
key:value
pairs
;
Read a
key
value
;
Example 1: Save key:value pairs
;
Example 2: ESP32 – Save/Read Network Credentials using the Preferences.h Library
;
Example 3: ESP32 – Remember Last GPIO State After RESET
;
Preferences.h Library
In a
previous tutorial
, we recommended using the EEPROM library to save data on flash memory. However, the EEPROM library is deprecated in favor of the
Preferences.h
library. This library is “installed” automatically when you install the ESP32 boards in your Arduino IDE.
The
Preferences.h
library is preferably used to store variable values through key:value pairs. Saving data permanently can be important to:
remember the last state of a variable;
save settings;
save how many times an appliance was activated;
or any other data type you need to save permanently.
If, instead of variables, you need to save files on the ESP32, we recommend using the filesystem (SPIFFS) instead. To learn how to save files in the ESP32 filesystem, you can read one of the following tutorials:
Install ESP32 Filesystem Uploader in Arduino IDE
ESP32 with VS Code and PlatformIO: Upload Files to Filesystem (SPIFFS)
Save Data Using Preferences.h Library
The data saved using preferences is structured like this:
namespace {
key:value
}
You can save different keys on the same namespace, for example:
namespace {
key1: value1
key2: value2
}
In a practical example, this configuration could be used to save your network credentials:
credentials {
ssid: "your_ssid"
pass: "your_pass"
}
In the preceding example,
credentials
is the namespace, and
ssid
and
pass
are the keys.
You can also have multiple namespaces with the same key (but each key with its value):
namespace1{
key:value1
}
namespace2{
key:value2
}
When using the
Preferences.h
library, you should define the data type you want to save. Later, if you want to read that data, you must know the saved data type. In other words, the data type of writing and reading should be the same.
You can save the following data types using
Preferences.h
: char, Uchar, short, Ushort, int, Uint, long, Ulong, long64, Ulong64, float, double, bool, string and bytes.
For more information, you can access the
Preferences.cpp file here
Preferences.h Library Useful Functions
To use the
Preferences.h
library to store data, first you need to include it in your sketch:
#include <Preferences.h>
Then, you must initiate an instance of the Preferences library. You can call it
preferences
, for example:
Preferences preferences;
After this, you can use the following methods to handle data using the
Preferences.h
library.
Start Preferences
The
begin()
method opens a “storage space” with a defined namespace. The
false
argument means that we’ll use it in read/write mode. Use
true
to open or create the namespace in read-only mode.
preferences.begin("my-app", false);
In this case, the namespace name is
my-app
Namespace name is limited to 15 characters.
Clear Preferences
Use
clear()
to clear all preferences under the opened namespace (it doesn’t delete the namespace):
preferences.clear();
Remove Key
Remove a key from the opened namespace:
preferences.remove(key);
Close Preferences
Use the
end()
method to close the preferences under the opened namespace:
preferences.end();
Put a Key Value (Save a value)
You should use different methods depending on the variable type you want to save.
Char
putChar(const char* key, int8_t value)
Unsigned Char
putUChar(const char* key, int8_t value)
Short
putShort(const char* key, int16_t value)
Unsigned Short
putUShort(const char* key, uint16_t value)
Int
putInt(const char* key, int32_t value)
Unsigned Int
putUInt(const char* key, uint32_t value)
Long
putLong(const char* key, int32_t value)
Unsigned Long
putULong(const char* key, uint32_t value)
Long64
putLong64(const char* key, int64_t value)
Unsigned Long64
putULong64(const char* key, uint64_t value)
Float
putFloat(const char* key, const float_t value)
Double
putDouble(const char* key, const double_t value)
Bool
putBool(const char* key, const bool value)
String
putString(const char* key, const String value)
Bytes
putBytes(const char* key, const void* value, size_t len)
Get a Key Value (Read Value)
Similarly, you should use different methods depending on the variable type you want to get.
Char
getChar(const char* key, const int8_t defaultValue)
Unsigned Char
getUChar(const char* key, const uint8_t defaultValue)
Short
getShort(const char* key, const int16_t defaultValue
Unsigned Short
getUShort(const char* key, const uint16_t defaultValue)
Int
getInt(const char* key, const int32_t defaultValue)
Unsigned Int
getUInt(const char* key, const uint32_t defaultValue)
Long
getLong(const char* key, const int32_t defaultValue)
Unsigned Long
getULong(const char* key, const uint32_t defaultValue)
Long64
getLong64(const char* key, const int64_t defaultValue)
Unsigned Long64
getULong64(const char* key, const uint64_t defaultValue)
Float
getFloat(const char* key, const float_t defaultValue)
Double
getDouble(const char* key, const double_t defaultValue)
Bool
getBool(const char* key, const bool defaultValue)
String
getString(const char* key, const String defaultValue)
String
getString(const char* key, char* value, const size_t maxLen)
Bytes
getBytes(const char* key, void * buf, size_t maxLen)
Remove a Namespace
In the Arduino implementation of Preferences, there is no method of completely removing a namespace. As a result, over the course of several projects, the ESP32 non-volatile storage (nvs) Preferences partition may become full. To completely erase and reformat the NVS memory used by Preferences, create a sketch that contains:
#include <nvs_flash.h>

void setup() {
nvs_flash_erase(); // erase the NVS partition and...
nvs_flash_init(); // initialize the NVS partition.
while(true);
}

void loop() {

}
You should download a new sketch to your board immediately after running the above, or it will reformat the NVS partition every time it is powered up.
Preferences.h – Save key:value Pairs
For a simple example on how to save and get data using
Preferences.h
, in your Arduino IDE, go to
File
>
Examples
>
Preferences
>
StartCounter
/*
ESP32 startup counter example with Preferences library.

This simple example demonstrates using the Preferences library to store how many times the ESP32 module has booted.
The Preferences library is a wrapper around the Non-volatile storage on ESP32 processor.

created for arduino-esp32 09 Feb 2017 by Martin Sloup (Arcao)

*/

#include <Preferences.h>

Preferences preferences;

void setup() {
Serial.begin(115200);
Serial.println();

// Open Preferences with my-app namespace. Each application module, library, etc
// has to use a namespace name to prevent key name collisions. We will open storage in
// RW-mode (second parameter has to be false).
// Note: Namespace name is limited to 15 chars.
preferences.begin("my-app", false);

// Remove all preferences under the opened namespace
//preferences.clear();

// Or remove the counter key only
//preferences.remove("counter");

// Get the counter value, if the key does not exist, return a default value of 0
// Note: Key name is limited to 15 chars.
unsigned int counter = preferences.getUInt("counter", 0);

// Increase counter by 1
counter++;

// Print the counter to Serial Monitor
Serial.printf("Current counter value: %u\n", counter);

// Store the counter t

Technologies used

ESP32ArduinoBLESPIArduino IDE

Hardware components

  • ESP32
  • Arduino

Software & tools

  • Arduino IDE
  • VS Code
  • PlatformIO
  • PlatformIO

What you get

  • Working project / hardware kit, tested before delivery
  • Complete source code with explanation
  • Project demo and guidance for your viva
  • Project report, PPT and IEEE paper support (on request)
Delivery & Payment
Delivery takes a minimum of two weeks from the date your inquiry is confirmed. Payment is in two parts: • 50% advance to start the project • Remaining 50% before delivery Note: • Documentation and PPT are not included by default • If you need documentation/PPT, it can be arranged for extra time and cost We'll confirm the exact timeline and cost with you after reviewing your requirements.