Search code examples
c++arduinoesp32

pointer to struct variable not saving to eeprom


I have some code to store configuration data to EEPROM. The data in the variable configuration can be printed to serial console but cannot be saved to EEPROM. I am using ESP32 (Arduino framework). The below code is the shortened version of the code found in this link.

#include <Arduino.h>
#include <EEPROM.h>

#define config_ver "VER01"

typedef struct {
  char version[10];
  int settings;
} configuration_type;

configuration_type configuration = {config_ver,50};

void saveconfig() {
  Serial.println("Saving configuration!!");
  for(int i=0; i < sizeof(configuration); i++) {
    char data = *((char*)&configuration + i);
    Serial.print(data);              //<----- Prints fine
    EEPROM.write(i,data);            //<----- Problem!!
  }
   Serial.println();
}

void setup() {
  Serial.begin(115200);
  saveconfig();

  Serial.println("Fetching EEPROM..!");
  for(int i = 0; i <= 20; i++) {
    Serial.print(EEPROM.read(i));
  }
  Serial.println("\n");
}

void loop() {

}

Output:

Saving configuration!!
VER01␀␀␀␀␀␀␀2␀␀␀        <--- prints fine!!
Fetching EEPROM..!
000000000000000000000           <--- Not saving to eeprom

Solution

  • ESP32 does not have EEPROM. It's just an emulation in flash memory. You need to commit your changes to move them from RAM to flash.

    Add EEPROM.begin(EEPROM_SIZE) with the appropriate size befor your writes to initialize EEPROM emulation.

    Add EEPROM.commit()after your writes to commit your writes to flash.

    Refer to the official example: https://github.com/espressif/arduino-esp32/blob/master/libraries/EEPROM/examples/eeprom_write/eeprom_write.ino

    Please note that EEPROM is deprecated. Use Preferences library instead.

    See https://github.com/espressif/arduino-esp32/tree/master/libraries/EEPROM