Skip to content

Instantly share code, notes, and snippets.

@pbosetti
Created June 29, 2009 14:30
Show Gist options
  • Save pbosetti/137629 to your computer and use it in GitHub Desktop.
Save pbosetti/137629 to your computer and use it in GitHub Desktop.
Pair of functions to read and write values of any type in Arduino's EEPROM memory.
/*
Functions to write and restore value of any type in Arduino's EEPROM
*/
#include <EEPROM.h>
// Functions
template <class T> int EEPROM_write(int ee, const T& value)
{
byte const *p = reinterpret_cast<byte const *>(&value);
int i;
for (i = 0; i < sizeof(value); i++)
EEPROM.write(ee++, *p++);
return i;
}
template <class T> int EEPROM_read(int ee, T& value)
{
byte *p = reinterpret_cast<byte *>(&value);
int i;
for (i = 0; i < sizeof(value); i++)
*p++ = EEPROM.read(ee++);
return i;
}
// Usage
#define VAR1_ADDR 100
#define VAR2_ADDR 200
unsigned int v1;
double v2;
EEPROM_write(VAR1_ADDR, 100);
EEPROM_read(VAR1_ADDR, v1);
EEPROM_write(VAR2_ADDR, 3.14);
EEPROM_read(VAR2_ADDR, v2);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment