STM32L4 Read Out Protection setup issues
Hi all,
I'm having issues getting ROP Level 1 setup on an STM32L412.
Below is the code which is run pretty soon after every reset.
After ROP has been set, and the system reset, ROP always reads back as 0xAA which leads to a boot loop of this function being run.
Strangely though, to erase/re-program the flash using a JLink, i first need to remove the ROP protection.
Any idea's what I'm doing wrong?
void Flash_Protect()
{
//check RDP level
uint32_t rdp_level = READ_REG(FLASH->OPTR) & FLASH_OPTR_RDP;
if (rdp_level == 0xAA)
{
//currently LEVEL0=0xAA (LEVEL1=0xBB)
//no read out protection is active
//disable flash read out to external devices
DEBUGS("FLASH IS NOT PROTECTED\n");
//flash unlock
if (READ_BIT(FLASH->CR, FLASH_CR_LOCK) != 0U)
{
//authorise the FLASH Registers access
WRITE_REG(FLASH->KEYR, 0x45670123U); //flash key 1
WRITE_REG(FLASH->KEYR, 0xCDEF89ABU); //flash key 2
//we'll assume it is unlocked
}
//flash OB unlock
if (READ_BIT(FLASH->CR, FLASH_CR_OPTLOCK) != 0U)
{
WRITE_REG(FLASH->OPTKEYR, 0x08192A3BU); //option byte key 1
WRITE_REG(FLASH->OPTKEYR, 0x4C5D6E7FU); //option byte key 2
}
//wait for flash to not be busy
while (READ_BIT(FLASH->SR, FLASH_SR_BSY) != 0) {}
//configure the RDP level in the option bytes register
MODIFY_REG(FLASH->OPTR, FLASH_OPTR_RDP, 0xBB); //set LEVEL1 (anything but 0xAA and 0xCC)
SET_BIT(FLASH->PCROP1ER, FLASH_PCROP1ER_PCROP_RDP); //set PCROP_RDP (req for LEVEL1)
//enable the OPTSTRT bit
SET_BIT(FLASH->CR, FLASH_CR_OPTSTRT);
//wait for flash to not be busy
while (READ_BIT(FLASH->SR, FLASH_SR_BSY) != 0) {}
//disable the OPTSTRT bit
CLEAR_BIT(FLASH->CR, FLASH_CR_OPTSTRT);
//lock flash
SET_BIT(FLASH->CR, FLASH_CR_LOCK);
//Launch the option byte loading
SET_BIT(FLASH->CR, FLASH_CR_OBL_LAUNCH);
while (READ_BIT(FLASH->SR, FLASH_SR_BSY) != 0) {}
//reset
DEBUGS("FLASH PROTECT RESET\n");
NVIC_SystemReset();
}
else
{
DEBUGS("FLASH IS PROTECTED\n");
}
}
Thanks in advance.
