How to write to STM32 Flash

b7031719 picture b7031719 · Jan 12, 2019 · Viewed 11.5k times · Source

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?

Answer

Barış İşbiliroğlu picture Barış İşbiliroğlu · Jan 22, 2019

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