writing in flash memory stm32 code example

Example 1: how to read write stm32 flash memory

//setup memory
// Modify Flash Address according to target MCU
HAL_FLASH_Unlock();
FLASH_Erase_Sector(11, FLASH_VOLTAGE_RANGE_3);
HAL_FLASH_Lock();

//write to memory
HAL_FLASH_Unlock();
uint8_t rdBuf[5];
uint8_t wrBuf[5] = {0x11, 0x22, 0x33, 0x44, 0x55};

uint32_t flashAddress = 0x080E0000;
for(uint32_t i=0; i<5; i++)
{
    HAL_FLASH_Program(FLASH_TYPEPROGRAM_BYTE, flashAddress, ((uint8_t *)wrBuf)[i]);
    flashAddress++;
}
HAL_FLASH_Lock();

//read
flashAddress = 0x080E0000;
for(uint32_t i=0; i<5; i++)
{
    *((uint8_t *)rdBuf + i) = *(uint8_t *)flashAddress;
    flashAddress++;
}

Example 2: how to write flash memory in stm32f030

// You can write into flash page but can not over write erase page before write again.
//https://stackoverflow.com/questions/47373317/how-to-write-erase-on-chip-flash-continuously-in-stm32f030-family
uint32_t pageAddress = 0x08008000;
  uint16_t buffer = 0xdddd;          // data buffer
  HAL_HAL_StatusTypeDef  status;

  while(1)
  { 
     HAL_FLASH_Unlock();              // unlock the flash memory in ST
     //FLASH_PageErase(pageAddress); 
     status=HAL_FLASH_Program(FLASH_TYPEPROGRAM_HALFWORD, pageAddress, 
     buffer);
     HAL_FLASH_Lock();                // Flash memory locked
  }

Tags:

C Example