clinkersectionsflash-memorystm32f4

STM32, variable stored in flash could not be updated in other file


I use a STM32F411RE. Since I've no more memory in my RAM. I decided to store large variable in my flash. For that I created a section in section.ld.

 .large_buffer: ALIGN(4)
    {
        . = ALIGN(4) ;
        *(.large_buffer.large_buffer.*)
        . = ALIGN(4) ;
    } >FLASH

In the main.c file, I declare the variable as follow :

uint8_t buffer[60 * 200] __attribute__ ((section(".large_buffer"), used));

At this point everything is OK, the buffer is not stocked in the RAM (bss), I can access it and rewrite it.

buffer[25] = 42;
printf("%d\n", buffer[25]); // 42

The problem comes when I want to edit the variable from an other file.

main.c

uint8_t buffer[60 * 200] __attribute__ ((section(".large_buffer"), used));

int main()
{
  myFunc(buffer);
}

other.c

myFunc(uint8_t* buffer)
{
    buffer[25] = 42;
    printf("%d\n", buffer[25]); // 0
}

buffer never change in another file (passed as parameter).

Did I miss something ?


Solution

  • You cannot write to flash memory the same way as you write to RAM, because of physical design of flash memories. To be exact you need to erase sector/page (let's say ~ 1-4kB, it's specified in your MCU datasheet). The reason is that flash are made that they retain state even if they're not powered, whenever you want to change any bit from value 0 -> 1 you need to erase whole sector (After erase all of bits will be set to 1).

    So you cannot use Flash as data memory, what you could do is use Flash as storing variables that are const (read-only) value, so any look-up tables will perfectly fit in there (usually compilers when you stat variable to const will put them inside of flash). How to write to flash you can read in Reference Manual of your MCU.