How to write to STM32 Flash

1

I want to write to flash Sector 11 of STM32F407VGT from my user code to store some data. I have used the stm32f4xx_hal_flash.c library. I first erase the sector using this code:

void Flash_Init(void)
{        
    FLASH_EraseInitTypeDef pEraseInit;

    pEraseInit.Banks = FLASH_BANK_1;
    pEraseInit.NbSectors = 1;
    pEraseInit.Sector = FLASH_SECTOR_10;
    pEraseInit.VoltageRange = FLASH_VOLTAGE_RANGE_3;
    pEraseInit.TypeErase = FLASH_TYPEERASE_SECTORS;

    if(HAL_FLASH_Unlock() == HAL_OK)
    {
        __HAL_FLASH_CLEAR_FLAG(FLASH_FLAG_EOP | FLASH_FLAG_OPERR | FLASH_FLAG_WRPERR | FLASH_FLAG_PGAERR | FLASH_FLAG_PGSERR );
        HAL_FLASHEx_Erase(&pEraseInit,0);
        HAL_FLASH_Lock();
    }
}

The program hangs when it reaches the HAL_FLASHEx_Erase(&pEraseInit,0); function. My scatter file looks like this:

LR_IROM1 0x08000000 0x01000000  {    ; load region size_region
  ER_IROM1 0x08000000 0x01000000  {  ; load address = execution address
   *.o (RESET, +First)
   *(InRoot$$Sections)
   .ANY (+RO)
  }
  RW_IRAM1 0x20000000 0x00020000  {  ; RW data
   .ANY (+RW +ZI)
  }
  RW_IRAM2 0x10000000 0x00010000  {
   .ANY (+RW +ZI)
  }
}

Is there something I must do first to allow this function to work?

stm32
stm32f4discovery
flash-memory
stm32f4
stm32-hal
asked on Stack Overflow Jan 12, 2019 by b7031719

1 Answer

0

You want to write sector 11 but your pEraseInit.Sector variable is FLASH_SECTOR_10 in your init function. So you should change FLASH_SECTOR_10 to FLASH_SECTOR_11. Also if you are use CubeMX you can try following write and read function without init function.

uint32_t flash_read(uint32_t address){
    return *(uint32_t*)address;
}

void flash_write(uint32_t address, uint32_t data){
    HAL_FLASH_Unlock();
    FLASH_Erase_Sector(FLASH_SECTOR_11,VOLTAGE_RANGE_1);
    HAL_FLASH_Program(FLASH_TYPEPROGRAM_WORD,address,data);
    HAL_FLASH_Lock();
}

You can see flash memoty map from here


User contributions licensed under CC BY-SA 3.0