Saving P2 program state when the power goes off?
bob_g4bby
Posts: 586
Very often, the state of a P2 based module requires saving at switch-off and restoring at switch on. We have several good libraries for flash or sd card file management now. However, that begs the question - how to save those critical project variables with the least amount of effort? Saving individual variables would seem to be more work than saving one structure of variables. A smartpin can be made to monitor the unregulated power voltage and the capacitor across the regulated supply ensures there's enough time to save and close the file before the P2 stops. Any hints and tips?
Cheers, bob

Comments
Interesting question ….
Maybe save entire hub to nonvolatile every so often and restore if reboot detected ?
That’d be easy but not sure if would be ok
If these "variables" don't change much and are acting more like configuration settings then possibly keep them stored in some i2c or SPI accessible NVRAM / EEPROM to begin with and read them back into RAM at run time and update the NVRAM whenever they change. If they change too much then the device may start to wear however, depending on the HW chosen.
If it’s just a few bytes., some new i2c rtc have user ram…
If all the variables that need saving at power-off are collected together in a structure in the top level object, @mystructure gives you the start address and sizeof(mystructure) gives you the byte count. Not too difficult to write that out to a file and read it back in on start-up.
I'm doing that in a game piece; every time the score or game time changes we save it to a battery-backed RTC module. On power-up (e.g., after a battery change in the middle of an 8-hour Airsoft game) the code looks for a running flag in the RAM. If that is set the scoring and game timer is copied from the RAM and the game auto starts, otherwise the game is reset to defaults and waits for a start single from the referee.
I have done this a couple of ways.
1. FRAM memory, writes quick, virtually no wear. If the additional access time doesn't slow things down too much, you can work from it for critical values, states, etc.
2. Exactly as you describe, monitoring actual power and using capacitive 'hang time' to write. I place the critical variables in a section where I can just copy the entire block of data to a file on power loss, and restore it over the block on power up. Know that capacitors age and you can't always control the drain. you might find someday that the hang time isn't enough. Corrupt data can be worse than no data.
Suppose to be 100% safe, should cycle through two copies of this data just to guard against the off chance that power is lost in the middle of a write …
A good excuse for a checksum?
You’d want something to make sure error was good you’d think…
But maybe the odds of bad write are so low, would depend on application ..