stm32 flash可以设置三个级别的读保护,实现读保护以后,flash将不可以从外部读取,如果想再次烧录代码,需要解除保护,解除读保护也可以使用代码,例如在代码中添加触发机制,比如串口收到某个特殊字符,则调用函数解除读保护。又或者使用软件,依然还是STM32 ST-LINK Utiltity,操作过程和打开读保护一致,只不过在选择等级的时候选择Level 0,则会将flash上的数据全部擦除,接着就可以重新烧代码。
读保护、关闭保护代码实现
在调试代码前,需要先了解怎样擦除读保护(isp\jlink\ram启动 解除保护)
/****************************************************************
* Function: Flash_EnableReadProtection
* Description: Enable the read protection of user flash area.
* Input:
* Output:
* Return: 1: Read Protection successfully enable
* 2: Error: Flash read unprotection failed
*****************************************************************/
uint32_t Flash_EnableReadProtection(void)
{
/* Returns the FLASH Read Protection level. */
if( FLASH_OB_GetRDP() == RESET )
{
/* Unlock the Option Bytes */
FLASH_OB_Unlock();
/* Sets the read protection level. */
FLASH_OB_RDPConfig(OB_RDP_Level_1);
/* Start the Option Bytes programming process. */
if (FLASH_OB_Launch() != FLASH_COMPLETE)
{
/* Disable the Flash option control register access (recommended to protect
the option Bytes against possible unwanted operations) */
FLASH_OB_Lock();
/* Error: Flash read unprotection failed */
return (2);
}
/* Disable the Flash option control register access (recommended to protect
the option Bytes against possible unwanted operations) */
FLASH_OB_Lock();
/* Read Protection successfully enable */
return (1);
}
/* Read Protection successfully enable */
return (1);
}
/****************************************************************
* Function: Flash_DisableReadProtection
* Description: Disable the read protection of user flash area.
* Input:
* Output:
* Return: 1: Read Protection successfully disable
* 2: Error: Flash read unprotection failed
*****************************************************************/
uint32_t Flash_DisableReadProtection(void)
{
/* Returns the FLASH Read Protection level. */
if( FLASH_OB_GetRDP() != RESET )
{
/* Unlock the Option Bytes */
FLASH_OB_Unlock();
/* Sets the read protection level. */
FLASH_OB_RDPConfig(OB_RDP_Level_0);
/* Start the Option Bytes programming process. */
if (FLASH_OB_Launch() != FLASH_COMPLETE)
{
/* Disable the Flash option control register access (recommended to protect
the option Bytes against possible unwanted operations) */
FLASH_OB_Lock();
/* Error: Flash read unprotection failed */
return (2);
}
/* Disable the Flash option control register access (recommended to protect
the option Bytes against possible unwanted operations) */
FLASH_OB_Lock();
/* Read Protection successfully disable */
return (1);
}
/* Read Protection successfully disable */
return (1);
}
在main开始后加入Flash_EnableReadProtection();即可实现读保护。在内部后台调用Flash_DisableReadProtection()解除保护。
- 在烧录前需要确保程序内无其他解除保护代码
- 烧录后需要掉电重启以运行程序(保护选项会在上电后自动载入一次)