Hello my Arduino fellows! How are you? The summer is hot! 🙂 In this post I would like to share with you two generic C++ template functions for reading from / writing to the Arduino EEPROM internal memory. I have used in the past these functions successfully in a project and I think that might be also useful to you.

It is a fact that just by looking the contents of a single byte in any memory we are not able to say what the data actually mean. The data or the bit pattern that appears has any meaning we want. It is always the context that gives meaning to data. It could be a memory address, an unsigned integer, a two’s complement signed integer, a machine opcode, an opcode operand, an IEEE-754 floating point number, an ASCII character, noise 🙂

The Arduino EEPROM memory can be used to write and read single bytes of data. So, as an example if we want to write an integer or a floating point number in EEPROM memory we have to do it byte by byte. Later on, if we want to read these back we have to do it also byte by byte.

This strategy is generalized and works identical for any data type. Inside the functions at first we are getting the address of the parameter reference and we cast it to “void *” in order to lose the type information. The next thing we do is to cast the remaining pointer to “byte *” so that we can handle the data byte by byte. Also, each time we use sizeof, in order to read or write the appropriate number of bytes depending on the data type.

Here, is the function that writes (byte by byte) any data structure using an EEPROM address:

// write to Arduino EEPROM a data structure.
template <class T> int
EEPROMGenericWrite (int addr, const T & value)
{
  const byte *p = (const byte *) (const void *) &value;

  int i;

  for (i = 0; i < sizeof (value); i++)
    EEPROM.write (addr++, *p++);

  return i;
}

Here, is the function that reads (byte by byte) any data structure using an EEPROM address:

// read from Arduino EEPROM a data structure.
template <class T> int
EEPROMGenericRead (int addr, T & value)
{
  byte *p = (byte *) (void *) &value;

  int i;

  for (i = 0; i < sizeof (value); i++)
    *p++ = EEPROM.read (addr++);

  return i;
}

Happy coding my friends!