Search code examples
arduinoeeprom

Store a long variable in EEPROM


My problem is the following:

I like to store data in an EEPROM like

char errorflag[] = "1234567"; 
i2c_eeprom_write_page(0x50, 0, (byte *)errorflag, sizeof(errorflag)); 

Perfect, no problems so far. But how can I save a long stored in a variable instead? Of course the following is not working, but it shows my what I like to do:

long long_variable = 1234567;
char errorflag[] = long_variable;  
i2c_eeprom_write_page(0x50, 0, (byte *)errorflag, sizeof(errorflag)); 

I tried quite a lot and it could not be to hard to figure it out but it seems I am to blind to see...


Solution

  • If you want to save the data as raw binary:

    long long_variable = 1234567;
    i2c_eeprom_write_page(0x50, 0, (byte *) long_variable, sizeof(long_variable)); 
    

    If you want to convert the variable to text and save that (including '\0' terminator):

    long long_variable = 1234567;
    char errorflag[16];
    sprintf(errorflag, "%ld", long_variable);
    i2c_eeprom_write_page(0x50, 0, (byte *) errorflag, strlen(errorflag) + 1);