Allocating memory in Flash for user data (STM32F4 HAL)

有些话、适合烂在心里 提交于 2019-11-27 18:52:57

Okay I found an answer on the ST forums thanks to clive1. This example works for an STM32F405xG.

First we need to modify the memory layout in the linker script file (.ld file)

Modify the existing FLASH and add a new line for DATA. Here I've allocated all of section 11.

MEMORY
{
  FLASH (RX)        : ORIGIN = 0x08000000, LENGTH = 1M-128K
  DATA (RWX)        : ORIGIN = 0x080E0000, LENGTH = 128k
  ...
  ...
}

Manual for editing linker files on the sourceware website

In the same file, we need to add:

.user_data :
{
  . = ALIGN(4);
     *(.user_data)
  . = ALIGN(4);
} > DATA

This creates a section called .user_data that we can address in the program code.

Finally, in your .c file add:

__attribute__((__section__(".user_data"))) const uint8_t userConfig[64]

This specifies that we wish to store the userConfig variable in the .user_data section and const makes sure the address of userConfig is kept static.

Now, to write to this area of flash during runtime, you can use the stm32f4 stdlib or HAL flash driver.

Before you can write to the flash, it has to be erased (all bytes set to 0xFF) The instructions for the HAL library say nothing about doing this for some reason...

HAL_FLASH_Unlock();

__HAL_FLASH_CLEAR_FLAG(FLASH_FLAG_EOP | FLASH_FLAG_OPERR | FLASH_FLAG_WRPERR | FLASH_FLAG_PGAERR | FLASH_FLAG_PGSERR );

FLASH_Erase_Sector(FLASH_SECTOR_11, VOLTAGE_RANGE_3);

HAL_FLASH_Program(TYPEPROGRAM_WORD, &userConfig[index], someData);

HAL_FLASH_Lock();
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!