2026-01-06 9:06 PM - last edited on 2026-01-07 6:34 AM by Andrew Neil
I have a requirement to implement CAN based bootloader in my STM32h503rbt6 controller. Right now iam working on the testing of Flash functions which i have written on my own.My flash write, read and erase all are working fine.but when iam erasing flash sector wise,here comes the problem.after sector 7, from sector 8 onwards with y function i cant abe to erase.but i want full memory controll over my st controller flash.then only i can decide which part of flash i can use for my bootloader and which part of flash i can use for my application.
HAL_StatusTypeDef Flash_Erase_Sector(uint32_t sector)
{
while (FLASH->NSSR & FLASH_SR_BSY);
if (FLASH->NSCR & FLASH_CR_LOCK)
{
FLASH->NSKEYR = FLASH_KEY1;
FLASH->NSKEYR = FLASH_KEY2;
}
/* Clear valid flags only */
FLASH->NSCCR =
FLASH_CCR_CLR_EOP
| FLASH_CCR_CLR_PGSERR
| FLASH_CCR_CLR_WRPERR;
FLASH->NSCR &= ~FLASH_CR_SNB_Msk;
FLASH->NSCR |= FLASH_CR_SER;
FLASH->NSCR |= (sector << FLASH_CR_SNB_Pos);
FLASH->NSCR |= FLASH_CR_START;
while (FLASH->NSSR & FLASH_SR_BSY);
FLASH->NSCR &= ~FLASH_CR_SER;
FLASH->NSCR |= FLASH_CR_LOCK;
return HAL_OK;
}Even after checking the datasheet, I could not identify why erasing sectors beyond sector 7 is failing.
Please help me identify the root cause and provide a proper solution.i have attached my project file
Edited to apply source code formatting - please see How to insert source code for future reference.
2026-01-06 9:14 PM - edited 2026-01-06 9:15 PM
> I could not identify why erasing sectors beyond sector 7 is failing. Please help me identify the root cause and provide a proper solution.
The STM32H503RBT6 only has 8 sectors per bank. You can't erase sectors that don't exist. That is the root cause.
The proper solution would be to restrict yourself to sectors that exist, or move to a chip with more memory if you need it.
Maybe you meant to erase sector 0 of bank 2 rather than "sector 8".
2026-01-06 9:32 PM
in that case how can i erase bank 2 sector 0.
2026-01-07 12:23 AM
Well, set the bank number to 1 and sector number to 0 in FLASH->CR.
2026-01-07 6:10 AM
I suggest using HAL_FLASHEx_Erase.
2026-01-07 6:55 AM - edited 2026-01-07 6:57 AM
As @TDK said, look at the HAL_FLASHEx_Erase() function:
The FLASH_EraseInitTypeDef structure contains fields to specify the Sector & Bank:
See: UM3132, Description of STM32H5 HAL and low-layer drivers
via: https://www.st.com/en/embedded-software/stm32cubeh5.html#documentation
via: https://www.st.com/en/microcontrollers-microprocessors/stm32h503rb.html#tools-software
@PRAKKU12 wrote:how can i erase bank 2 sector 0..
As @gbm suggested, you select the Bank in the Flash configuration register:
via: https://www.st.com/en/microcontrollers-microprocessors/stm32h503rb.html#documentation