arduinoesp32flash-memoryeeprom

Write String to permanent flash memory of Arduino ESP32


I want to write some text into the flash memory of an Arduino ESP32. It works kinda but not as I want it to.

void writeString(const char* toStore, int startAddr) {
  int i = 0;
  for (; i < LENGTH(toStore); i++) {
    EEPROM.write(startAddr + i, toStore[i]);
  }
  EEPROM.write(startAddr + i, '\0');
  EEPROM.commit();
}

My call

writeString("TEST_STRING_TO_WRITE", 0);

only writes TEST into the memory. I do not understand why. Is that because of the _? Or am I missing something different?

Here is the used LENGTH macro

#define LENGTH(x) (sizeof(x)/sizeof(x[0]))

and the method I use to read the string from the memory again (which seems to work correctly):

String readStringFromFlash(int startAddr) {
  char in[128];
  char curIn;
  int i = 0;
  curIn = EEPROM.read(startAddr);
  for (; i < 128; i++) {
    curIn = EEPROM.read(startAddr + i);
    in[i] = curIn;
  }
  return String(in);
}

Solution

  • Where on earth did you get that LENGTH macro from? It’s surreal.

    sizeof will not do what you want here. It’s a compile-time function that computes the storage requirements of its argument. In this case it should return the length in bytes of a character pointer, not the string it points to.

    You want to use strlen(), assuming your char* is a properly terminated C string. Add one to make sure the ‘\0’ at the end gets stored, too.

    #define LENGTH(x) (strlen(x) + 1)