esp32-preferences

Save ESP32 variables and the Preferences library

  • 4 min

The preferences.h library is a tool provided by the Arduino framework for the ESP32 that facilitates storing and retrieving configuration data in the device’s flash memory.

It is designed as a replacement for the EEPROM library, serving as an alternative for saving variables in non-volatile memory (NVS), which persists across ESP32 reboots.

The preferences.h library optimizes flash memory usage and allows fast and efficient access to stored data. It is designed to work with many small values, rather than a few large ones.

Using preferences.h

Include the Library

To start using preferences.h, include the library in your program:

#include <Preferences.h>
Copied!

Create a Preferences Object

Before using preferences.h, you need to create a Preferences object that will represent the preferences storage namespace. You can do it as follows:

Preferences preferences;
Copied!

Initialize and Open the Storage Namespace

Before accessing preferences, you must initialize and open the storage namespace. This is done by calling the begin() method of the Preferences object:

bool begin(const char * name, bool readOnly=false, const char* partition_label=NULL)
Copied!
  • name: Namespace name. Maximum length is 15 characters.
  • readOnly:
    • false will open the namespace in read/write mode.
    • true will open the namespace in read-only mode. If omitted, the namespace will open in read/write mode.
  • partition_label: name of the NVS partition where the namespace will be opened.

If omitted, the namespace will be opened in the “nvs” partition.

preferences.begin("mis_variables", false);
Copied!

Store and Retrieve Values

Once the storage namespace is open, you can store and retrieve values using the putX and getX methods respectively, where X represents the data type you want to store/retrieve (e.g., putInt, getInt, putFloat, getFloat, etc.).

// Store an integer
preferences.putInt("valor_entero", 42);

// Retrieve an integer
int miEntero = preferences.getInt("valor_entero", 0); // The second argument is the default value if the preference is not found

// Store a float value
preferences.putFloat("valor_flotante", 3.14);

// Retrieve a float value
float miFlotante = preferences.getFloat("valor_flotante", 0.0);
Copied!

Delete a Variable

bool remove("mi_variable");
Copied!

Close the Storage Namespace

Remember to close the storage namespace once you are done working with the preferences:

preferences.end();
Copied!

Code Example

#include <Preferences.h>
#include <WiFi.h>

const char* ssid = "nombre-de-la-red";
const char* password = "contraseña-de-la-red";

Preferences preferences;

void setup() {
  preferences.begin("mis_variables", false);
  preferences.putString("nombre_red", ssid);
  preferences.putString("password_red", password);
  preferences.end();
  
  // Rest of the initialization code, WiFi connection, etc.
}
Copied!