SparkFun Forums 

Where electronics enthusiasts find answers.

Your source for all things Atmel.
By jolijar
#105201
Can someone please explain the code found here to me?
http://www.arduino.cc/playground/Code/E ... teAnything
I want to store several numbers in the EEPROM but I have been unable to get it to work
I need it to store several numbers like this "41.914768218994140" and then be able to recall it.

I have been messing around with it for several hours without success.
If I comment out the writeanything and change the float lats value shouldn't it recall the old value in the eeprom and display the old value?

Code: Select all
#include <EEPROM.h>

template <class T> int EEPROM_writeAnything(int ee, const T& value)
{
    const byte* p = (const byte*)(const void*)&value;
    int i;
    for (i = 0; i < sizeof(value); i++)
	  EEPROM.write(ee++, *p++);
    return i;
}

template <class T> int EEPROM_readAnything(int ee, T& value)
{
    byte* p = (byte*)(void*)&value;
    int i;
    for (i = 0; i < sizeof(value); i++)
	  *p++ = EEPROM.read(ee++);
    return i;
}




struct config_t
{
    float lats;
} configuration;

void setup()
{
  
  Serial.begin(9600);
   
    // ...
}
void loop()
{
    
    float lats = 41.914768218994140;
    
    EEPROM_readAnything(81, configuration);
    EEPROM_writeAnything(81, configuration);
    
   Serial.println(lats, 15);

    delay(15000);
}
By rrpilot
#105229
I can see two little mistakes in your code.
Code: Select all
float lats = 41.914768218994140;
should be:
Code: Select all
configuration.lats = 41.914768218994140;
and change:
Code: Select all
    EEPROM_readAnything(81, configuration);
    EEPROM_writeAnything(81, configuration);
to
Code: Select all
    EEPROM_writeAnything(81, configuration);
    EEPROM_readAnything(81, configuration);
and finally change:
Code: Select all
Serial.println(lats, 15);
to:
Code: Select all
Serial.println(configuration.lats, 15);
That should accomplish what your after.