Search code examples
arduinoesp32

writing and reading object into esp32 flash memory, arduino


I'm trying to store some data encapsulated into the object in the flash memory of ESP32.

It seems that writing object into the memory by putBytes works good, but I haven't an idea how to read it.

The way I tried to do this doesn't work...

#include <Preferences.h>
Preferences eeprom;

typedef struct {
  long  var1 = -1;
  long  var2 = -1;
  long  var3 = 0;
  byte  var4 = 0;
} someObject;

someObject object_[4][24];
someObject object_1_[4][24];

void setup() {
  Serial.begin(115200);
  eeprom.begin("Settings", false);

  object_[0][0].var1  = 25889;
  object_[0][0].var2   = 25890;
  object_[0][0].var3 = 25891;

  object_[1][2].var1  = 25892;
  object_[1][2].var2   = 25893;
  object_[1][2].var3 = 25894;

  eeprom.putBytes("someObject", &object_[4][24], sizeof(object_[4][24]));

  Serial.print("sizeof(object_[4][24]) = "); Serial.println(String(sizeof(object_[4][24])));

  size_t schLen = eeprom.getBytes("someObject", NULL, NULL);

  Serial.print("sizeof(someObject) = "); Serial.println(String(schLen));

  char buffer[schLen];

  eeprom.getBytes("someObject", &object_1_[4][24], schLen); // I know use of "&" is wrong, but havn't idea to fix it

  Serial.println("--------**********************************");
  Serial.println(String(object_[0][0].var1));
  Serial.println(String(object_[0][0].var2));
  Serial.println(String(object_[0][0].var3));

  Serial.println("--------");
  Serial.println(String(object_1_[1][2].var1));
  Serial.println(String(object_1_[1][2].var2));
  Serial.println(String(object_1_[1][2].var3));

  Serial.println("===========================================");

  Serial.println(buffer);
}

void loop() {}

Thanks in advance for any idea!


Solution

  • Like in the example usage of Preferences (https://github.com/espressif/arduino-esp32/blob/master/libraries/Preferences/examples/Prefs2Struct/Prefs2Struct.ino), you need to read the bytes into the buffer before casting to a struct.

    In your case, you are declaring the buffer but never using it. Since you know the exact size of the array, you should be able to directly copy it from buffer to object_.

    char buffer[schLen]; // prepare a buffer for the data
    eeprom.getBytes("someObject", buffer, schLen);
    memcpy(object_, buffer, schLen);