Emx flash endurance

I need to store a counter value once every 10 seconds or so as an ExtendedWeakReference, so that on power up a counter starts where it left off.

Should I have concerns with flash endurance if doing this? If so what alternatives do I have without writing to something external (sdcard etc.)?

Think I may have found the answer with the BatteryRAM class.

I have a question about the following code however (I haven’t tried yet):


        public static void WritePersistentCounters()
        {
            byte[] buf = Reflection.Serialize(Counters, typeof(PersistentCounters));
            BatteryRAM.Write(0,buf,0,buf.Length);
        }

        public static void InitializePersistentCounters()
        {
            byte[] buf = new byte[4];
            BatteryRAM.Read(0, buf, 0, 4);
            Counters = (PersistentCounters)Reflection.Deserialize(buf, typeof(PersistentCounters));
        }

Looks like I have to allocate a fixed number of bytes to properly serialize my object…? I’m sure it has to be longer than 4 bytes (pulled from the wiki example), unless there’s a way to not have to allocate for my object.

Yes, you should be concerned with the endurance of the flash. The spec says it’s guaranteed for a minimum of 10,000 cycles, 100,000 cycles typically. The RAM has some load levelling capabilities so you would see better than that, but it’s not the right way.

As to your serialisation example, when you store the serialised object, first store the length of the serialised object (as an int) then the serialised object itself.

Then when you get the object back out, you start by reading the length as an int, then instantiate and read in the serialised object itself to that length.

Something like:


public static void WritePersistentCounters()
        {
            byte[] buf = Reflection.Serialize(Counters, typeof(PersistentCounters));
            // Save length as bytes
            BatteryRAM.Write(0,buf,0,buf.Length);
        }
 
        public static void InitializePersistentCounters()
        {
            // Read length as int (4 bytes long - from sizeof(int))
            
            byte[] buf = new byte[read_in_serialised_length];
            BatteryRAM.Read(0, buf, 0, read_in_serialised_length);
            Counters = (PersistentCounters)Reflection.Deserialize(buf, typeof(PersistentCounters));
        }

Good idea on storing the length first. Thanks for the help.