EuroDuino: Saving to EEPROM

Confess your sins here. Prayers optional.

Moderators: Kent, BrotherTheo

Post Reply
User avatar
Ultra Wiggler
Posts: 963
Joined: Wed Oct 06, 2010 12:45 pm
Location: Portland, Oregon

EuroDuino: Saving to EEPROM

Post by BrotherTheo » Sat Mar 21, 2015 1:09 pm

(copied from yahoo group)

Hey everybody--

One function you may want to include in your program is saving data in EEPROM. There is a library for that, called oddly enough EEPROM. It has two functions: write and read. So far so good.

But the puppies and bunnies ends there. The EEPROM library reads and writes bytes only. And to make matters worse, you must give it an address to write to or read from. This sounds complicated, and to a degree it is. Lets walk through the way I did it.

First, put all the variables to be saved in a structure.

struct foo {
byte doh;
int rae;
float mee;

This groups all the data in one container. Now it gets a but tricky: to turn all that non-byte data into bytes, we use a union:

union {
struct foo thisFoo; //access as a struct
byte fooSave[sizeof(foo)]; //access as an array of bytes
} SaveMore;

Unions are handy gizmos. They allow you to access data in different ways. In our case we have our structure:

struct foo thisFoo; //access as a struct

And we have an array of bytes:

byte fooSave[sizeof(foo)]; //access as an array of bytes

Both are accessing the same data, but in different ways. The sizeof operator returns the number of bytes in the variable, in our case the structure foo.

To access these variables in the program it looks like this:

SaveMore.thisFoo.doh = 23;
SaveMore.thisFoo.rae = 4298;
SaveMore.thisFoo.mee = 3.14159;

SaveMore refres to the union, thisFoo refers to the struct method of accessing the data, and doh, etc, are the elements of the structure to access. I know it looks complicated, but it works, and has other benefits like data hiding. But that's another article.

Now for the fun part: saving to eeprom. All we have to do is access the byte array of the union and step through it with a for loop:

for(index=0;index<sizeof(foo);index++) {

The for loop starts at zero, increments by one each iteration, and stops when the sizeof foo is reached. In other words, step though each element of the array from start to end. In this case the index is also the address for the eeprom locarion to write, which is convenient.

Reading back the data is just as easy:

for(index=0;index<sizeof(foo);index++) {
SaveMore.fooSave[index] =;

Its really the same code as before except using read instead of write.

I wrote a sketch to demonstrate this. It is called eeprom_test. Check it out.

Don't forget to jump in and have fun!

--Brother Theo
Human, all too human...

Post Reply

Return to “Circuit Abbey”