Showing results for 
Search instead for 
Did you mean: 

Store data in internal flash without erasing whole page

Associate III

Hi, I would like to know method and sample code storing data without erasing whole memory page. I do refer example FLASH_EraseProgram, but i have wrote program that almost finish up the flash memory, if i erase a page, a 2KB page, it will erase my code map, and cause the program hardfault, the MCU i use is STM32C0 with 16KB flash. So, may i have some info to solve it? Thanks.



>may i have some info to solve it?

very easy : take next cpu with more flash ! 🙂


If you feel a post has answered your question, please click "Accept as Solution".

Which part# specifically? What does the DEV_ID report as? See Part# details reported in Cube Programmer

There might be one of the die with 32 KB, of which 16 KB is tested. Check if accessing 0x08004000 hard faults, or shows data in STM32 Cube Programmer.

You can incrementally write so it's possible to journal a structure a couple of times beyond where you code ends.

As long as none of the involved code is in the last sector, you can probably copy content to RAM, erase and when re-write, but obviously that's more challenging.

Getting the next part# up might be a better long term strategy if you're already at 98-99% utilization

Tips, Buy me a coffee, or three.. PayPal Venmo
Up vote any posts that you find helpful, it shows what's working..
Pavel A.
Evangelist III

This can be easier than you think)) If you use the CubeIDE debugger to load the program, (by default) it won't fill the unused end of the last page. So you can just write there without erase. Just mind the needed alignment: 8 bytes (64-bit). Also note that STM32C0 has OTP memory, you can use it (program only once, of course).



i try to write data to 0x8003C00, if erase a single page 7 of the memory block which start with 0x08003800, then it will erase my code which end in 0x080039A0. It might more challenging to me as a beginner.image.png


void writeFlash(void){
FLASH_EraseInitTypeDef flash_erase_struct = {0};
flash_erase_struct.TypeErase = FLASH_TYPEERASE_PAGES;
flash_erase_struct.Page = 7;  //0x08003800
flash_erase_struct.NbPages = 1;
uint32_t  error_status = 0;
HAL_FLASHEx_Erase(&flash_erase_struct, &error_status);


Above is my code and i would like to know, how to write structured data(64bit) into flash? As each of my variables are 16bits data, so i would like to save memory.

Use a structure or array to hold your data in a byte packed efficient form.

Cast to a 64-bit pointer and write data the data as multiple blocks of 8-bytes.

Tips, Buy me a coffee, or three.. PayPal Venmo
Up vote any posts that you find helpful, it shows what's working..

hi, thanks for the information