Clear backup SRAM

Hi guys, we are having trouble updating a batch of devices where we have significantly changed SRAM variables. After update they tend to panic reset. We can catch this and boot to safe mode but of course SRAM is retained. As they are located around the country plus covid, it will be difficult to power them off. Is there an easy way to programmatically clear the SRAM and start afresh?

Ideally looking for something similar to EEPROM.clear()
Otherwise do you think something like this should work?

retained byte SRAMcontents[3068];
void setup() {
  memset(SRAMcontents, 0, sizeof(SRAMcontents));

Yes, that should work.

What I prefer to do is put all of my retained variables in a struct with magic bytes. For example:

const uint32_t RETAINED_MAGIC = 0x2cbd6d39;
typedef struct {
  uint32_t magic;
  int value1;
  int value2;
  char value3[32];
} RetainedData;

retained RetainedData retainedData;

Before using the data you check that retainedData.magic == RETAINED_MAGIC. If data was uninitialized, the magic won’t match and you know you need to reinitialize. When you update the firmware, you change the magic bytes to make sure the data get reinitialized.

It’s also not a bad idea to put the sizeof(RetainedData) in the struct, which takes care of the case that you added a retained member and forgot to change the magic bytes.


In addition to that, when you have a considerable size struct you could also add a checksum field to ensure data integrity.


@rickkas7 Oh that is a fine solution! Plus it helps to keep track of all the retained variables scattered around the code.

Then to reset, it would be a case of using memset(&retainedData, 0, sizeof(retainedData)); right?

I’m sure there will be times we forget to change the magic number. I hesitate to attempt to improve it by setting it to __system_product_version so it changes automatically :slight_smile:
Or/and use a checksum variable like @ScruffR suggested.