Here are my thoughts on how to utilise the EEPROM for storing the system state. The main Idea behind the following “algorithm” is that we record the numbers of how often the button is pressed. Further we use a Power Cycle ID (short PCID) and a cyclic buffer to store the state.
The PCID is incremented (+1 mod 256) everytime the device is powered up. Due to the mod 256 The PCID ranges from 0 to 255 and after 255 starts again at 0.
The cyclic buffer holds 254 bytes and the buffer pointer is incremented (+1 mod 255) everytime when a byte is written.
What now happens it that everytime we press the button (remark this presented algorithm only works for devices with one button) we write the PCID at the pointer of the cyclic buffer. Additionally the PCID is also written everytime the device is powered up.
I will give now an example with an reduced 15 bytes buffer:
0,1,1,2,2,2,3,3,3,3,4,5,6,7,8
so what story does this buffer tells us, well
at first power up there was no button pressed – at 2nd the button was pressed one time, at 3rd two times, at 4th 3 times – then the device was powered up 5 times without a pressed button.
By reading the cyclic buffer we also find out what the last PCID was. In our case 8 was the last PCID, because 8 > 0 – we further have carefully choosen our cyclic buffer to be 254 bytes long – so even if we warp around from 256 to 0 we (at worst case) have possibility to obain the last PCID because the difference hast to be greater or equal to two.
PCID = x[i] where (x[i mod 255] – x[(i + 1) mod 255]) mod 256 >= 2
In this way we can determin our last PCID and we also know how often the button was pressed before the last power cycle and therefore we can restore our system state.
As our buffer holds 254 bytes and we have assured 300 000 writecycles in our EEPROM – this translates to apr. 76 Mio button activations. – way more than the mechanics of the button would be able to handle. UPDATE: looking in the STM8 Datasheet it shows that we have a stoarage granularity of 4 Bytes. – this needs to be taken into account when implementing the cyclic buffer (for example to blow up the buffer from 255 bytes up to 1020 bytes)