1

I'm facing a problem can't be able to resolve to store an array of struct in nvs.

I have this structure composed of variable length String:

typedef struct
 {
     String Name;
     String Surname;
     String Status;
     String Expiry;
 }  EpromTags;

EpromTags arraytag[50];

void setup()
{
  //should load arraytag from EEPROM here
 } 

In other routines I have this data coming from a remote server, so I'm saving it to me arraytag


for (int i=0, i<50,i++)
 {
    arraytag[i].Name = valuename[i];
    arraytag[i].Surname = valuesurname[i];
    arraytag[i].Status = valuestatus[i];
    arraytag[i].Expiry = valueexp[i];
 }  

//should save to arraytag to EEPROM here

The idea is to load the value of the structure to men on arrive and load back on setup.

I have been able to write single elements to EEPROM but I'm finding difficulties in saving this array of struct.

can someone drive me in the right directions or have suggestions?

giorgio
  • 105
  • 1
  • 8

1 Answers1

3

The String class handles a char array buffer allocated in heap memory. The object of class String only has a pointer to this buffer. If you store a String object to EEPROM, you don't store the buffer and after retrieving the object the pointer is not valid.

Use C strings (zero terminated character arrays) of predefined size to store a struct with string in EEPROM.

typedef struct
 {
     char name[NAME_MAX_LENGTH];
     char surname[SURENAME_MAX_LENGTH];
     char status[STATUS_LENGTH];
     char expiry[EXP_LENGTH];
 }  EpromTags;

To save any data type you can use EEPROM.put(). To read it back you use EEPROM.get(). So you can use a straight forward EEPROM.put(arraytag) to store all 50 items of the array and EEPROM.get(arraytag) to read it back.

The size of the struct is sizeof(EpromTags). The size of the array is count of items multiplied by the size of the item.

Note that the ESP32 EEPROM library emulates the EEPROM in flash memory and requires to call EEPROM.begin() and EEPROM.commit(). See the examples of the ESP32 EEPROM library on how to use it.

Juraj
  • 3,490
  • 4
  • 18
  • 25