STM32F1系列在程序中进行写保护设置

发布于 2020-09-10  570 次阅读


//OB_WRP_PAGES36TO39
#define FLASH_PAGE_TO_BE_PROTECTED (0x00007fff)
static FLASH_OBProgramInitTypeDef OptionsBytesStruct;
void app_ob_flash_write(void)
{
    /* Unlock the Flash to enable the flash control register access *************/
    HAL_FLASH_Unlock();

    /* Unlock the Options Bytes *************************************************/
    HAL_FLASH_OB_Unlock();

    /* Get pages write protection status ****************************************/
    HAL_FLASHEx_OBGetConfig(&OptionsBytesStruct);

    if (((~OptionsBytesStruct.WRPPage) & FLASH_PAGE_TO_BE_PROTECTED) != FLASH_PAGE_TO_BE_PROTECTED)
    {
        /* Enable the pages write protection **************************************/
        OptionsBytesStruct.OptionType = OPTIONBYTE_WRP;
        OptionsBytesStruct.WRPState = OB_WRPSTATE_ENABLE;
        OptionsBytesStruct.WRPPage = FLASH_PAGE_TO_BE_PROTECTED;
        if (HAL_FLASHEx_OBProgram(&OptionsBytesStruct) != HAL_OK)
        {
            goto _exit;
        }

        /* Generate System Reset to load the new option byte values ***************/
        HAL_FLASH_OB_Launch();
    }


    _exit:
    /* Lock the Options Bytes *************************************************/
    HAL_FLASH_OB_Lock();
    /* Lock the Flash to disable the flash control register access (recommended
     to protect the FLASH memory against possible unwanted operation) *********/
    HAL_FLASH_Lock();

}

int flash_ob_test(void)
{
    app_ob_flash_write();
    return 0;
}

一沙一世界,一花一天堂。君掌盛无边,刹那成永恒。