void read_protect(void) { if(FLASH_GetReadOutProtectionStatus() != SET) { FLASH_Unlock();//不解锁FALSH可能会导致无法正常设置读保护 FLASH_ReadOutProtection(ENABLE); } }
/** * @brief Erases the FLASH option bytes. * @note This functions erases all option bytes except the Read protection (RDP). * @note This function can be used for all STM32F10x devices. * @param None * @retval FLASH Status: The returned value can be: FLASH_ERROR_PG, * FLASH_ERROR_WRP, FLASH_COMPLETE or FLASH_TIMEOUT. */ FLASH_Status FLASH_EraseOptionBytes(void) { uint16_t rdptmp = RDP_Key; FLASH_Status status = FLASH_COMPLETE; /* Get the actual read protection Option Byte value */ if(FLASH_GetReadOutProtectionStatus() != RESET) { rdptmp = 0x00; } /* Wait for last operation to be completed */ status = FLASH_WaitForLastOperation(EraseTimeout); if(status == FLASH_COMPLETE) { /* Authorize the small information block programming */ FLASH->OPTKEYR = FLASH_KEY1; FLASH->OPTKEYR = FLASH_KEY2; /* if the previous operation is completed, proceed to erase the option bytes */ FLASH->CR |= CR_OPTER_Set; FLASH->CR |= CR_STRT_Set; /* Wait for last operation to be completed */ status = FLASH_WaitForLastOperation(EraseTimeout); if(status == FLASH_COMPLETE) { /* if the erase operation is completed, disable the OPTER Bit */ FLASH->CR &= CR_OPTER_Reset; /* Enable the Option Bytes Programming operation */ FLASH->CR |= CR_OPTPG_Set; /* Restore the last read protection Option Byte value */ OB->RDP = (uint16_t)rdptmp; /* Wait for last operation to be completed */ status = FLASH_WaitForLastOperation(ProgramTimeout); if(status != FLASH_TIMEOUT) { /* if the program operation is completed, disable the OPTPG Bit */ FLASH->CR &= CR_OPTPG_Reset; } } else { if (status != FLASH_TIMEOUT) { /* Disable the OPTPG Bit */ FLASH->CR &= CR_OPTPG_Reset; } } } /* Return the erase status */ return status; }
void FLASH_ReadOutProtection_Enable(void) // If FLASH readout protection not already set, enable protection and reset device // NOTES: The user area of the Flash memory can be protected against read by untrusted code. //Protection is enabled only for firmware compiled with flag RELEASE_PUBLIC set (see makefile). //When readout protection is set debugging via JTAG is not possible any more. //If the read protection is set while the debugger is still connected through JTAG/SWD, apply a //POR (power-on reset) instead of a system reset (without debugger connection). { if (FLASH_GetReadOutProtectionStatus() != SET) { #ifdef RELEASE_PUBLIC // HINT: define is done via makefile FLASH_Unlock(); if (FLASH_ReadOutProtection(ENABLE) != FLASH_COMPLETE) // set readout protection { // ERROR: could not program read protection } else NVIC_SystemReset(); // protection set --> reset device to enable protection #else // output warning message #endif } }