Electronic – STM32 Flash mass erase from IAP

flashstm32

It might be a silly question but I can't figure out in what cases a flash mass erase from in-application programming (IAP) is relevant, as it would erase the user code as well?

For STM32 devices, ST provides example code in reference manuals like this one:

A.2.4 Mass erase sequence code example

/* (1) Set the MER bit in the FLASH_CR register to enable mass erasing */
/* (2) Set the STRT bit in the FLASH_CR register to start the erasing */
/* (3) Wait until the BSY bit is reset in the FLASH_SR register */
/* (4) Check the EOP flag in the FLASH_SR register */
/* (5) Clear EOP flag by software by writing EOP at 1 */
/* (6) Reset the PER Bit to disable the mass erase */
FLASH->CR |= FLASH_CR_MER; /* (1) */
FLASH->CR |= FLASH_CR_STRT; /* (2) */
while ((FLASH->SR & FLASH_SR_BSY) != 0) /* (3) */
{
 /* For robust implementation, add here time-out management */
}
if ((FLASH->SR & FLASH_SR_EOP) != 0) /* (4)*/
{
 FLASH->SR = FLASH_SR_EOP; /* (5) */
}
else
{
 /* Manage the error cases */
}
FLASH->CR &= ~FLASH_CR_MER; /* (6) */

I don't understand how the CPU can reach the instructions from (3) to (6).

Shouldn't they be erased already?

Best Answer

The program might not be running from flash. The STM32 can run code from SRAM or external memory (via FMC); code running from these locations could safely* erase flash memory.

Some STM32 parts also have two banks of flash memory. Code could be running from one bank and erasing the other bank.

*: Well, mostly safely. A power failure during an erase/program cycle would leave the part blank.