EEPROMWriteAnything - EEPROMReadAnything

Hello,

I used this code to upload something to my eeprom:

#include <EEPROM.h>

void setup() {
  // put your setup code here, to run once:
  String test = "hello";
  sizeof(test);
  EEPROM_writeAnything(0, test);
}

void loop() {
  // put your main code here, to run repeatedly:

}

template <class T> int EEPROM_writeAnything(int ee, const T& value)
{
    const byte* p = (const byte*)(const void*)&value;
    unsigned 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;
    unsigned int i;
    for (i = 0; i < sizeof(value); i++)
          *p++ = EEPROM.read(ee++);
    return i;
}

Now my question is how would i use EEPROMReadAnything to Serial.println(the_string_i_saved_in_the_eeprom);

regards,

Are you sure, that you saved the string in EEPROM? Normally you can't write a string "plain" into EEPROM, but you have to break the string into bytes. Then read byte after byte and concatenate it to the original string again.

Afaik there might be a method using arrays or so, but I have no experience with that.

I love this sketch. One more example of the capital-S String class totally screwing things up. The totally useless sizeof() statement is just icing on the cake there.

Now my question is how would i use EEPROMReadAnything to Serial.println(the_string_i_saved_in_the_eeprom);

Short answer is you can’t, because the String class uses dynamic allocation and you never actually stored the contents of the string in EEPROM because of that.

rpt007:
Are you sure, that you saved the string in EEPROM?
Normally you can’t write a string “plain” into EEPROM, but you have to break the string into bytes. Then read byte after byte and concatenate it to the original string again.

Afaik there might be a method using arrays or so, but I have no experience with that.

Isn’t that what this function does?

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

Isn't that what this function does?

Did you read the description of that library: http://playground.arduino.cc/Code/EEPROMWriteAnything

They say this library saves "any data type", but nobody said: "Strings".

Look at the reply of @Jiggy-Ninja:

Short answer is you can't, because the String class uses dynamic allocation and you never actually stored the contents of the string in EEPROM because of that.