STM32 Write and read from FLASH


I've read and worked through the exercises in the Discovery book, and had a lot of fun doing so.
I'd now like to try writing and read from the FLASH memory on the STM32.

I have the STMicroelectronics F3 development board (as suggested by Discovery).

From the STM32F303VCT6 reference:

  • There is 256 Kbytes of Flash memory in the STM32F303xB/C

Flash memory interface (FLITF) features:

  • Read interface with prefetch buffer (2 × 64-bit words)
  • Option byte loader
  • Flash program/Erase operation
  • Read/Write protection
  • low-power mode

Before I even continue with questions, can I clarify if it's even possible to write user data to flash at run-time, since our program BIN/ELF is also occupying space there?

And If at all possible, which registers should I look into?

sure, it is. Somehow your burner/programmer is also writing data (your code) to the flash during "runtime", isn't it?

That's correct and the tricky part. You have to ensure not to modify existing data or you will have bad times.
I would suggest to ensure during compile time, that your binary does not exeed let's say 248kB so you can use the last 8kB for user data. A proper linker script should be able to handle that.

For a rough guideline on how to write to flash, see this stackoverflow post. Be aware, that flash have a limited life cycle, e.g. you can only rease pages 100k-ish times. Then they are bad and tend to loose data.

If you have fun soldering I would recommend to use an I2C or SPI eeprom attached to the I2C pins and storing information there. Shouldn't be that hard to solder 4 pins (VCC, Gnd, SCL, SDA).

Thanks for your reply @hellow, I'm reading between the lines here and hearing; don't write user data to the integrated flash because:

  1. Firstly because it's not that straight forward
  2. Risk of overriding program data
  3. A ~$5 EEPROM (~1 million cycles) is cheaper to replace than a ~$30 STM32F3 development board (~100K cycles).

I agree - I'll use a EEPROM instead.


5$ is pretty expensive ^^ You can get an AT24 incl breakout board for ~70cent delivered (40 days delivery though...)! (Aliexpress).

If you choose the AT24 series, there is a handy crate that does stuff for you

1 Like

For some tasks, I don't see any problems with using the built-in flash (100k cycles is quite a lot). I could be wrong, but I think you could just edit memory.x to limit the maximum amount of flash that would be used for code, the rest you could just use for whatever purpose you like.