How to set RDP level 1 via software on STM32G030
I would like to increase the code readout protection level from 0 to 1 programmatically in an STM32G030. I must be doing something silly and if anyone sees it, I'd be grateful. I've stepped through it with the debugger and the flash and option byte locks are indeed removed. The write to the option register doesn't show up in the debugger (still shows 0xAA), There are no errors in the FLASH SR or CR registers after the OPTSTART bit is set. The debugger loses connection when OBL_LAUNCH is set (presumably due to the reset). After the reset, the RDP byte in the flash OPTR is still set to 0xAA. It is still 0xAA after the device is power cycled. The code is:
// Set code readout protection
__disable_irq();
// unlock flash memory (LOCK bit in FLASH_CR)
FLASH->KEYR = 0x45670123;
FLASH->KEYR = 0xCDEF89AB;
// wait for flash unlocked
while (FLASH->CR & FLASH_CR_LOCK);
// clear option lock (OPTLOCK bit in FLASH_CR)
FLASH->OPTKEYR = 0x08192A3B;
FLASH->OPTKEYR = 0x4C5D6E7F;
// wait for option bytes unlocked
while (FLASH->CR & FLASH_CR_OPTLOCK);
// Set flash readout protection level 1
MODIFY_REG(FLASH->OPTR, FLASH_OPTR_RDP, 0xBB);
// NOTE: errata 2.2.3: boot mode selection pin cannot be enabled at the
// same time as RDP level 1 or the uC will intermittently fail to boot
// So use nBOOT0 bit to select main flash memory for boot
SET_BIT(FLASH->OPTR, FLASH_OPTR_nBOOT_SEL | FLASH_OPTR_nBOOT0);
// write the desired values
while (FLASH->SR & FLASH_SR_BSY1); // wait for flash ready
FLASH->CR |= FLASH_CR_OPTSTRT; // start write of options
while (FLASH->SR & FLASH_SR_BSY1); // wait for flash ready
FLASH->CR |= FLASH_CR_OBL_LAUNCH; // read/use new options
In digging into the HAL code, I thought this might be a problem with the option byte region being write protected, but I don't see it and the write attempt doesn't set the WRPERR bit in the FLASH->SR (no error bits are set).
Thanks!
