How to enable Read-out protection in your firmware using Cube library functions

Blog Post created by fillon.nicolas Employee on Feb 22, 2017



Recently I had to write a sample code for a customer in order to turn on the read out protection of the flash to a level 1.


I did it for a STM32L15x Nucleo or Discovery board but it can be easily ported to another family of STM32.


The code is simple: if the level of readout protection is not set to 1, it will set it to level 1.


If the STM32 RDP is already at level 1 it will do nothing.


I have attached my code zipped.


Unzip it at:




Use the IDE of your choice to build and load the code : IAR, Keil or SW4STM32.

Then once code is built and loaded.


Reset the board so that code will execute.


Now try to use ST-LINK Utility to access the flash: the tool will tell you that the read operation cannot be made because the readout protection has been activated.







Here is the important part of the code to execute:


  /* Unlock the Flash to enable the flash control register access *************/

  /* Unlock the Options Bytes *************************************************/

  /* Get pages write protection status ****************************************/

  /* Check if readoutprtection is enabled ***********************/
  if((OptionsBytesStruct.RDPLevel) == OB_RDP_LEVEL_0)
    OptionsBytesStruct.OptionType= OPTIONBYTE_RDP;
    OptionsBytesStruct.RDPLevel   = OB_RDP_LEVEL_1;
    if(HAL_FLASHEx_OBProgram(&OptionsBytesStruct) != HAL_OK)
      /* Error occurred while options bytes programming. **********************/
      while (1)


    /* Generate System Reset to load the new option byte values ***************/

  /* Lock the Options Bytes *************************************************/