Skip to content

Instantly share code, notes, and snippets.

@thegabriele97
Created November 29, 2021 15:52
Show Gist options
  • Save thegabriele97/52e78ab163cc5c7e4c821120782c2f70 to your computer and use it in GitHub Desktop.
Save thegabriele97/52e78ab163cc5c7e4c821120782c2f70 to your computer and use it in GitHub Desktop.
uint32_t Flash_Write_Data (uint32_t StartPageAddress, uint32_t *Data, uint16_t numberofwords) {
static FLASH_EraseInitTypeDef EraseInitStruct;
uint32_t PAGEError;
int sofar=0;
/* Unlock the Flash to enable the flash control register access *************/
HAL_FLASH_Unlock();
/* Fill EraseInit structure*/
EraseInitStruct.TypeErase = FLASH_TYPEERASE_SECTORS;
EraseInitStruct.Sector = 11;
EraseInitStruct.NbSectors = 1;
EraseInitStruct.Banks = 0;
EraseInitStruct.VoltageRange = FLASH_VOLTAGE_RANGE_3;
if (HAL_FLASHEx_Erase(&EraseInitStruct, &PAGEError) != HAL_OK) {
/*Error occurred while page erase.*/
return HAL_FLASH_GetError ();
}
/* Program the user Flash area word by word*/
while (sofar<numberofwords) {
if (HAL_FLASH_Program(FLASH_TYPEPROGRAM_WORD, StartPageAddress, Data[sofar]) == HAL_OK) {
StartPageAddress += 4; // use StartPageAddress += 2 for half word and 8 for double word
sofar++;
} else {
/* Error occurred while writing data in Flash memory*/
return HAL_FLASH_GetError ();
}
}
/* Lock the Flash to disable the flash control register access (recommended
to protect the FLASH memory against possible unwanted operation) *********/
HAL_FLASH_Lock();
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment