Introduction
This (rather short) 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 this all 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:
NEW_EEPROM_VARIABLE(int, 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:
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:
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:
eeprom_write<EEPROM_Variables, e_var1>(128); int var2 = eeprom_read<EEPROM_Variables, e_var2>();
Points of Interest
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