简体   繁体   中英

Write to STM32 internal flash fails

On my stm32 mcu there is no eeprom. So, I am using internal flash to save one byte user data to retain it between power cycles.I am doing it the following way,

  1. Add Data section in memory in the linker script
MEMORY { 
   RAM (xrw) : ORIGIN = 0x20000000, LENGTH = 8K 
   FLASH (rx) : ORIGIN = 0x8000000, LENGTH = 64K 
   DATA (xrw) : ORIGIN = 0x800F800, LENGTH = 2K //Allocated one full flash page 
}
  1. Create user data section
    .user_data : 
     { . = ALIGN(4); 
       *(.user_data)
       . = ALIGN(4);
     } >DATA
  1. Create a variable to store in flash
    attribute((section(".user_data"))) const uint8_t userConfig[10]
  1. Write data using following functions,
    HAL_FLASH_Unlock();
    
    __HAL_FLASH_CLEAR_FLAG(FLASH_FLAG_EOP | FLASH_FLAG_OPERR | FLASH_FLAG_WRPERR | FLASH_FLAG_PGAERR | FLASH_FLAG_PGSERR );
    
    FLASH_PageErase(FLASH_PAGE_31);
    
    HAL_FLASH_Program(FLASH_TYPEPROGRAM_DOUBLEWORD, (uint32_t)&userConfig[index], someData);
    
    HAL_FLASH_Lock();

When I try to write to the flash it fails with PGSERR flag set.

  1. 0x0800 3800 - 0x0800 3FFF is bank 7 not bank 11.

  2. &userConfig[index] is generally wrong as the memory is programmed in this micro in 64bits words and the address has to be aligned to the 8 bytes boundary.

ALWAYS READ THE DOCUMENTATION before programming microcontrollers. Use of the magic libraries does not free you from knowing your hardware.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM