MSP430FR5969: Using PERSISTENT with C++ class

Part Number: MSP430FR5969

Hello. I am working on sensor firmware where the state for the sensor logic is encapsulated in a C++ "Sensor" class. I would like the state of the class to be persistent across power cycles but initialized on program load. I'm aware that in C this can be done with the PERSISTENT pragma if the class was replaced with a struct and I initialize it manually in the declaration and omit a sensor_init() function call in the program. With C++ however I am concerned that the constructor for the class will run and reinitialize the class every time the MCU resets. In C I can manually omit the call to the init function, in C++ I am not sure how replicate this. Is there a way I can get my desired behavior using a C++ class or is the only option to do it the C way?

  • Have your constructor look for a "magic number" - I like 0xDEADBEEF - in the data. If that is present, no init is necessary. If that is not present, init your PERSISTENT area with the magic number and your initial values.

  • You can achieve this in C++ without completely reverting to raw C!. The primary C++ concern is the hidden initialization of static/global objects by the compiler's startup routines. To avoid running the constructor and overwriting your persistent state on every reset, you can use a few tailored embedded C++ approaches:

    • You can encapsulate your Sensor class inside a wrapper struct. This allows you to place the wrapper into a PERSISTENT memory section, while ensuring the underlying state is safely separated from auto-initializing C++ constructors.
    • f your entire Sensor class needs to be marked as PERSISTENT, you must prevent the compiler from generating a constructor at program startup. Declare the class as a Plain Old Data (POD) structure/class with trivial or deleted constructors. Once the linker places it in the persistent memory section, you can "attach" your C++ class methods to the persistent data at runtime using placement new
    • If your sensor states only need to survive hardware resets (but wipe on full power loss), most embedded toolchains support placing a C++ object into a .noinit section using compiler attributes.

    Also, I think Keith has a good idea on achieving this as well. Hope this helps!

    -Brian

  • Thanks Brian! I ended up going with option one and its good enough for me. Thanks for sharing option two, maybe I can investigate that one and learn something new!

**Attention** This is a public forum