Circular buffer on flash

From Stm32World Wiki
Jump to navigation Jump to search
Green Pill rev. c

As is commonly known, many STM32 MCUs, including the STM32F103 used on the Blue Pill boards, contains more non-volatile flash storage than is advertised by ST. On my own Green Pill board a STM32F103C8 MCU is used. This MCU has got - according to ST, 64kB of flash, but in reality it is identical to the STM32F103CB and it does have 128kB of flash. This is documented in quite some detail here.

This naturally leads to the question if this extra flash could be used to store for example sensor data, and well, the answer to that question is: of course it can.

Before we dive into this in more detail, let me stress a big fat warning. Just because something can be done that does not necessarily translate into that being a good idea. In the STM32F103x8 datasheet, we find the following table:

STM32F103 Data Retention.png

In other words, while the number is probably much higher, ST only guarantees 10000 erase cycles on their internal flash. This value is much lower than a dedicated flash which will often guarantee in excess of 100000 erase cycles.

And this is where a "circular" buffer comes in. If, for example, we were to use 64 kB of flash to store a circular buffer of 32bit sensor data, and we made sure to spread the writes out over the entire flash range, that would leave 64 kB / 4 = 16384 "update locations". If for example we were to store a sensor reading every second it would take 16384 seconds before we would need to repeat the cycle. A year is 31557600 seconds, so 31557600 / 16384 ≈ 1926. So each year it will go through roughly 2000 cycles. With ST guaranteeing a minimum of 10000 cycles that means it will take in excess of 5 years before it breaks.

STM32 Read internal temperature and voltage reference

STM32F103xx Flash Page Layout.png