I am working on designing energy meter using PIC18F46K80. When the power goes off the meter store data on the flash memory (credit and so). Meter power supply stores enough energy to supply the microcontroller for 2 seconds to ensure the writing will be correct.
The writing it self is incremental in memory. I mean I write only on empty memory location (0xFFFF). when the reserved memory is full (I reached the last location). I erase all memory pages and start writing from the first location.
My problem is: when I attached a debugging tool that supply the microcontroller 5v directly I don't have any energy store. when this debugging tool is removed while a writing event is occurring, I find that all memory page is erased to 0xFFFF. I knew that writing in an empty flash memory is only by resetting the bits (0) in memory locations according to the data ( if I understand this in the right way). And when we need to rewrite in the same memory location we need to erase the whole page and rewrite again.
The question is how could writing in one empty memory location in the flash memory erase the whole page?
Note: I knew it is not a good practice to write such data in flash memory. It is better to use the EEPROM. However, currently I am stick with this design I can't modify to use internal or external EEPROM. Another thing which I will post in other question is the security of storing the credit and private key in external EEPROM.