FAQ & Terms of UseFAQ & Terms Of Use   Wiggler RadioMW Radio   Muff Wiggler TwitterTwitter   Support the site @ PatreonPatreon 
 SearchSearch   RegisterSign up   Log inLog in 

EuroDuino: Saving to EEPROM
MUFF WIGGLER Forum Index -> Circuit Abbey  
Author EuroDuino: Saving to EEPROM
(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
MUFF WIGGLER Forum Index -> Circuit Abbey  
Page 1 of 1
Powered by phpBB © phpBB Group