Section 11: Preferences Library

You are viewing Section 11 of 13

Remember when we saw that the settings in the Trinamic driver get cleared out on reset?

That would be a very annoying problem to deal with because your device can get reset any time for many reasons such as a power outage.

When using Arduino, we create variables, for example x = 0. Then somewhere along the way we change it to x = 5. But when you restart your device, it gets reset to x=0 because all variables are held in memory which gets wiped clean.

So we use the preferences library, which you can learn more about here:

What it does is store our values in a special partition that is located on the flash memory. When the device restarts, this flash is not cleared, just like your sketch, and is always stored in the flash memory.

First we include the library on line 7

#include <Preferences.h>

Then we create a Preferences object. In this case we will call it preferences but it can be any name you want

Preferences preferences

In setup, we need to start it up. The first word “local” can be anything you want as well, it is just a name.

preferences.begin("local", false);

Then we run the function load_preferences(); in order to load all of our saved data into each variable. 

Go to the memory.h tab to see what variables get loaded.

In this function we take our variables and set them to equal what is stored in the preferences flash memory. This allows our variables to be reloaded correctly each time there is a restart.

Let's look at the stall variable

stall = preferences.getInt("stall", 10);

we set the stall value to what is stored inside the "stall" preferences key. Teh prefrerences library uses key/value pairing. Note that the "stall" key inside of preferences is different than the stall variable we are using. Just in case there is no "stall" key or value, then we need a default value, which we set to 10. That means if "stall" is empty then stall=10.

How do we create the "stall" key and add a value to it?

Go to the tab ESPUI.h on line 51

preferences.putInt ("stall", stall);

Here we will store the value of stall into the Preferences key "stall".

A better example is this:

preferences.putInt ("stall", 20);

We use the preferences.putInt class to assign the value 20 to the "stall" key.

Upon reset, we assign the value of key "stall" to our stall variable. In this case stall=20.

stall = preferences.getInt("stall", 10);

There are different types of values you can save such as 


Which will save a string like a WiFi password.

Do not mix up getInt and putInt. They look very similar but are very very different. putInt will save the value and getInt will retrieve it.



 Course Sections:

Leave a comment