Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / IoT / Arduino

Arduino: Static EEPROM Memory Management

5.00/5 (1 vote)
13 Aug 2015CPOL2 min read 9.8K   53  
Easy, compile-time manager of EEPROM variables

Introduction

This tip will be covering a solution I wrote to the 'problem' that arises when you need to use EEPROM memory for your Arduino project. Because there is no such thing as EEPROM-identifiers, i.e. names that refer to addresses in the EEPROM memory space, you have to manage these addresses manually. This can quickly lead to less readable code and errors when you accidentally get the offset wrong.

This one-header library lifts this responsibility by adding special EEPROM-pseudo-variables and providing read- and write- functions to interact with these variables. Because all this happens at compile-time, the resources of your MCU won't be affected in any way.

Using the Code

Step 1: Declare New EEPROM Variables

To declare EEPROM variables, you can choose whether to use a macro or not. If you do, these 'declarations' look like the following:

C++
NEW_EEPROM_VARIABLE(int, e_var1);  // EEPROM variable of type 'int', called 'e_var1'
NEW_EEPROM_VARIABLE(byte, e_var2); 

The NEW_EEPROM_VARIABLE macro simply hides an empty struct declaration. If you don't like using this macro, the above can also be written as:

C++
struct e_var1: EEPROM_Variable__<int> {};
struct e_var2: EEPROM_Variable__<byte> {};

These two versions are exactly the same, so pick the one you like best.

Step 2: Register the Variables

Once the variables have to be declared, they must be registered:

C++
using EEPROM_Variables = RegisterVariables__<
    e_var1,
    e_var2
>;

For those unfamiliar with the added C++11 syntax, this is simply a typedef. The name EEPROM_Variables can be changed to anything you like, though it will be used in the next step.

Step 3: Reading/Writing

The functions eeprom_read and eeprom_write are provided to read from and write to these variables. For instance:

C++
eeprom_write<EEPROM_Variables, e_var1>(128);         // set e_var1 to 128
int var2 = eeprom_read<EEPROM_Variables, e_var2>();  // read e_var2 and store in local variable

Points of Interest

Because these EEPROM variables are not actually variables, but types, all the above declarations (not the function calls from step 3 obviously) need to be in the global namespace.

The code behind this uses C++11 features, so your compiler has to be configured for C++11. When using the Arduino IDE, refer to this page to find out how to configure it to use these features.

History

  • August 13, 2015: First draft
  • August 14, 2014: Added remark about the global namespace (Points of Interest)

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)