Setting Read Protection level 1 from firmware
I have tried following the examples in the reference manual and online, but am having issues!
This is on STM32F030C8T6, on a custom PCB and connected to debugger over SWD:
void readProtect_lvl1(void){
//read protection is in effect on next power cycle
while ((FLASH->SR & FLASH_SR_BSY) != 0) {} //wait for any ongoing flash operation to complete
if ((FLASH->CR & FLASH_CR_LOCK) != 0)
{
FLASH->KEYR = 0x45670123UL; //magic number removes control register lock
FLASH->KEYR = 0xCDEF89ABUL; //magic number removes control register lock
}
while ((FLASH->SR & FLASH_SR_BSY) != 0) {} //wait for flash operation to complete
if ((FLASH->CR & FLASH_CR_OPTWRE) == 0)
{
FLASH->OPTKEYR = 0x45670123UL; //magic number sets option byte write access
FLASH->OPTKEYR = 0xCDEF89ABUL; //magic number sets option byte write access
}
FLASH->CR |= FLASH_CR_OPTER; // must erase option byte first
FLASH->CR |= FLASH_CR_STRT; //start flash again
while ((FLASH->SR & FLASH_SR_BSY) != 0) {}
while ((FLASH->SR & FLASH_SR_EOP) == 0) {}; //wait for end of operation
FLASH->SR |= FLASH_SR_EOP; //clear end of operation flag
FLASH->CR &= ~FLASH_CR_OPTER; //clear erase bit
FLASH->CR |= FLASH_CR_OPTPG; // set programming bit !!PGERR (FLASH_CR_bit2)!!
OB->RDP = 0xBB; //any value other than 0xCC or 0xAA sets lvl1 read protection !!after this operation, OB->RDP = 0xfe01 !!
FLASH->CR &= ~FLASH_CR_OPTPG; // reset option byte programming bit
FLASH->CR |= FLASH_CR_LOCK; // reset the control register lock bit
};
some notes from debugging:
- good: flash key sequence clears FLASH_CR_LOCK
-good: flash option key sequence sets write enable OPT_WRE
-good: FLASH_CR_OPTER resets option byte to 0xFFFF
-good: clearing FLASH_CR_OPTER, no errors (looking at flash status register, PGERR is not set)
-first problem: setting FLASH_CR_OPTPG does work (bit changes), but PGERR flag is set (flash status register)
-second problem: after "OB->RDP = 0xBB" operation, the result after that line executes is: OB->RDP = 0xfe01, is one bit is getting in, the complement is set by hardware during programming and then it seems the RDP byte locks?
I'm still achieving lvl1 read protection, (since any value other than 0xAA or 0xCC sets lvl1), however I would like to understand what I'm doing wrong! Thank you for your help
