Writing data to the Arduino's onboard EEPROM

Charlie Walton picture Charlie Walton · Mar 11, 2013 · Viewed 8.9k times · Source

I am currently trying to write a function to store data to the EEPROM on my Arduino. So far I am just writing a specified string and then reading it back when the program first runs. I am trying to store the length of the string as the first byte and my code is as follows;

#include <EEPROM.h>
#include <LiquidCrystal.h>

LiquidCrystal lcd(8, 13, 9, 4, 5, 6, 7);
char string[] = "Test";

void setup() {
    lcd.begin( 16, 2 );
    for (int i = 1; i <= EEPROM.read(0); i++){ // Here is my error
      lcd.write(EEPROM.read(i));
    }
    delay(5000);
    EEPROM_write(string);
}

void loop() {
}

void EEPROM_write(char data[])
{
    lcd.clear();
    int length = sizeof(data); // I think my problem originates here!
    for (int i = 0; i <= length + 2; i++){
        if (i == 0){
            EEPROM.write(i, length); // Am I storing the length correctly?
            lcd.write(length);
        }
        else{
            byte character = data[i - 1];
            EEPROM.write(i, character);
            lcd.write(character);
        }
    }
}

The problem I am having is when I read the first byte of the EEPROM, I get the supposed length value. However, the loop only runs three times. I have commented some points of interest in my code, but where is the error?

Answer

angelatlarge picture angelatlarge · Mar 12, 2013

You are indeed correct, on many counts, I think. Try this for writing:

// Function takes a void pointer to data, and how much to write (no other way to know)
// Could also take a starting address, and return the size of the reach chunk, to be more generic
void EEPROM_write(void * data, byte datasize) {
   int addr = 0;
   EEPROM.write(addr++, datasize);
   for (int i=0; i<datasize; i++) {
      EEPROM.write(addr++, data[i]);
   }
}

You would call it like this:

char[] stringToWrite = "Test";
EEPROM_write(stringToWrite, strlen(stringToWrite));

To read then:

int addr = 0;
byte datasize = EEPROM.read(addr++);
char stringToRead[0x20];          // allocate enough space for the string here!
char * readLoc = stringToRead;
for (int i=0;i<datasize; i++) {
    readLoc = EEPROM.read(addr++);
    readLoc++;
}

Note that this is not using the String class developed for Arduino: reading and writing that would be different. But the above should work for char array strings.

Note however, that while EEPROM_write() looks generic now, it isn't really, since addr is harcoded. It can only write data to the beginning of EEPROM.