Cloud String - Eeprom Dump

Hi,

I am trying to dump some data from the EEPROM to String that I expose via the Cloud Variable function. The code compiles but doesnt work.

char *someString = "";

void setup() {
    int data;
    Spark.variable("someString", someString, STRING);
    
    for(uint8_t i=0; i<8; i++) {
        data = EEPROM.read(i);
        someString += data + ' ';
    } 
}

void loop() {

}

The idea is that it reads each byte from the EEPROM and then appends it to the STRING.

So theoretically the output would be “0 0 0 0 0 0 0 0”. Instead I get “”.

I tried a couple of other things with no success.

Anyone have any ideas?

“+=” on a pointer changes the value of the pointer, it does not manipulate any data. Note that ' ' is the space character, but that " " is the nul-terminated string [array of char] consisting of a space (and the nul-terminator '\0').

To concatenate C-style strings you can use strcat().

You are not allocating any memory for someString. I suggest char someString[100] = ""; To add a char & a space to a string I suggest

// index 0 is the 1st char, index 1 is the 2nd char of the string
someString[ strlen(someString)+2 ] = '\0'; // the NUL character
someString[ strlen(someString)+1 ] = ' ';
someString[ strlen(someString) ] = (char)data;

Is data really an int? If so then I suggest you sprintf() to convert the int to an ascii rep thereof.

sprintf( someString, "%s%d ", someString, data);

or if data is a char

sprintf( someString, "%s%c ", someString, (char)data);

Also note that your string must remain nul-terminated. My 1st example does that, and sprintf obeys the nul-termination convention. sprintf uses a lot of memory.

3 Likes

Nice explanation @psb777! :wink:

1 Like

Thank you! Works as expected! Here is the code for anyone else in question (see psb777’s post)

Ah, you’ve implemented the 1st solution additionally. The three lines with strlen in them are not needed if you use sprintf(). You just need the sprintf() line. Indeed, the last line ought to make it buggy because the sprintf() has lengthened the string! In my 1st non-sprintf() soln the nul-termination doesn’t get replaced until the last step. In short: Either use the three lines with strlen in them or use the sprintf.

char someString[50] = "";

void setup() {
    int data;
    Spark.variable("someString", someString, STRING);

    for(uint8_t i=0; i<8; i++) {
        data = EEPROM.read(i);
        sprintf( someString, "%s%d ", someString, data);
    } 
}

void loop() {
}
1 Like

Thanks. I didnt fully understand what sprintf does so I assumed I needed both.

I will do some reading on how sprintf() works, but it does what I need it to do. Thank you very much!