Search code examples
carmstructureshadoweeprom

Shadow copy for a data structure stored in EEPROM


I am using ARM GCC for a STM32F105RC processor.
In my application I have now something like:

typedef struct
{
  uint16_t coinValue;
  uint8_t  minimumCoins;
} MIN_COIN_RENDERING;

typedef struct
{
  uint16_t coinValue;
  uint8_t  hopperType;
  uint8_t  motorDelay;
} CONFIG_HOPPER;

typedef struct
{
  MIN_COIN_RENDERING minCoinRendering[10];
  CONFIG_HOPPER hopper[5];
  uint8_t reservedFFU[X];
  //
  uint16_t crc;
} APPLICATION_CONFIG; // MUST have 128 bytes!

The first problem is how to determine correctly the number of bytes reserved FFU (marked above with an X).
If you say: X = 128 - (10 x 3 + 5 x 4 + 2) = 76, well this is not true!
The correct value for X is 66, because the compiler aligns the fields in the structures (at least with the compiler's default settings).
The overall structure must have 128 bytes, as it will be stored-to / restored-from an EEPROM. The structure is used as a shadow copy of what we have in EEPROM...

My question: Is there a way (better, flexible) to have a shadow copy (for the EEPROM) without having to mess with the reservedFFU size each time I add a new field (or change something) in the APPLICATION_CONFIG structure ?


Solution

  • The fact that you want something of a fixed size with data at specific offsets sounds a lot like you want something that's part-structure, part-array. Provided you're prepared to treat the crc slightly differently, why not have exactly that!

    typedef union
    {
      struct {
        MIN_COIN_RENDERING minCoinRendering[10];
        CONFIG_HOPPER hopper[5];
      };
      uint16_t raw[64];
    } APPLICATION_CONFIG;
    
    // Then e.g.
    APPLICATION_CONFIG config;
    config.hopper[3].motorDelay = 7; // Thanks to anonymous structures
    uint16_t *crcptr = &config.raw[63];