Search code examples
c++stm32flash-memory

Why are the FLASH pages not being cleared on the stm32?


I am programming the stm32(l412kb), where one function clears an area of FLASH ready for later overwriting. The area of flash being cleared is in the second half of the storage - page 35 - for 6 pages. The stm32l412kb has 64 pages of 2KB flash.

I have been following the reference manual, page 83.

The clearing of flash worked once, but then after a few attempts, never again, which then lead to a code change so I'm not sure if even the code is correct now! When the code worked, the stm IDE showed the memory had been reset to 0, but when the code 'failed' the value shown is a default 0xFFFFFFFF, despite the code running through fine.

The code is:

int clearFlash(uint8_t numberOfPages, uint8_t firstPageNumber){
    HAL_FLASH_Unlock();

    FLASH->SR &= ~(FLASH_FLAG_PGSERR | FLASH_FLAG_PGAERR | 
    FLASH_FLAG_WRPERR |FLASH_FLAG_OPERR | FLASH_FLAG_EOP); //Clearing Error Flags
    //Looping through clearing enough space. Flash is cleared in 2KB pages.
    for (int i = 0; i<numberOfPages; i++){
        while(FLASH->SR & FLASH_SR_BSY); //Hold While Busy
        while((FLASH->SR & FLASH_SR_PGSERR)); //PGSERR should not be set 
        FLASH->CR |= FLASH_CR_PER; //Set erase process

        FLASH->CR &= ~FLASH_CR_PNB_Msk; //Clear address mask

        FLASH->CR |= ((firstPageNumber+i)<<FLASH_CR_PNB_Pos); //place in address
        FLASH->CR |= FLASH_CR_STRT; //Start clear
    }
    HAL_FLASH_Lock();
    return 1;
}

The variable firstPageNumber is passed the value 35, and numberOfPages is worked out from a file size (6 pages). If there are any ideas for my faults, your contributions are much appreciated.

Many thanks in advance, Harry


Solution

  • For the STM32, the erase/clear state is all '1'. So a value of 0xFFFF FFFF is the correct value to observe after erasing memory. In the reference manual you provided, refer to the top of page 85 where it states

    erase value 0xFFFF FFFF