Search code examples
arraysarduinoeeprom

How to write an array of non primitive objects to Arduino EEPROM then read the array into memory each time the program starts


I am developing a pill reminder for Electronics Final year project. I need to store the name of the pill, the number of times it is taken, the hours it is taken during and whether it is currently active or not. I created a class pill as below, and stored the pills in an array:

class Pill{
    public:
        String pillName = "Nothing";
        boolean pillTaken = true;
        int hours[6]; 
        boolean active = false;
        int count = 0; 
};

Pill pills[6];

Now I want to persist this data in the Arduino EEPROM, how can I write the array of pills to the EEPROM and read the data into memory each time program starts. Also, I need to update the array each time a command to modify a pill is received, putting the new values.


Solution

  • @Galarzaa90 has pointed you to the right information, however, the EEPROM lib will not work with the String class.

    Why?

    Because the actual String data is not stored in the objects memory space, it simply contains a pointer to some dynamic memory elsewhere.

    If you save a String object you will save its length, buffer size and pointer to data. However, when you restart your duino and load the String from EEPROM, the pointer will be pointing to... anywhere but where you expect.

    You'll need to use a cstring/ char array which means the string data is actually stored inside the Pill class.