2026-03-01 1:55 PM
There is a bug in the above mentioned function in stm32f1xx_hal_flash_ex.c file. The function has a uint32_t type parameter WriteProtectPage which determines the flash page chunks to disable the write protection of. On my F103 MCU it means every bit corresponds to 4 pages (each page is 1 Kbyte, total of 128 Kbyte flash memory).
This line then combines the currently write protected pages with WriteProtectPage (0 means protected, 1 means unprotected):
WriteProtectPage = (FLASH_OB_GetWRP() | WriteProtectPage);
The function then slices WriteProtectPage up into 4 pieces (4 WRP option bytes):
WRP0_Data = (uint16_t)(WriteProtectPage & OB_WRP_PAGES0TO31MASK);
WRP1_Data = (uint16_t)((WriteProtectPage & OB_WRP_PAGES32TO63MASK) >> 8U);
WRP2_Data = (uint16_t)((WriteProtectPage & OB_WRP_PAGES64TO95MASK) >> 16U);
WRP3_Data = (uint16_t)((WriteProtectPage & OB_WRP_PAGES96TO127MASK) >> 24U);
It then erases the option byte area (returns it to reset state ?):
status = HAL_FLASHEx_OBErase();
And here comes the bug. It writes the previously created variables into the real WRP option bytes, but since they have been returned to their reset state (0xFF e.g. write protection disabled) their individual bits can never become 0s because of the |= operator:
OB->WRP0 |= WRP0_Data;
OB->WRP1 |= WRP1_Data;
OB->WRP2 |= WRP2_Data;
OB->WRP3 |= WRP3_Data;
The operators used should be &= as it's done in FLASH_OB_EnableWRP function.
Solved! Go to Solution.
2026-03-01 3:52 PM
> OB->WRP0 |= WRP0_Data;
> OB->WRP1 |= WRP1_Data;
> OB->WRP2 |= WRP2_Data;
> OB->WRP3 |= WRP3_Data;
These lines don't appear in the latest stm32f1xx_hal_flash_ex.c file:
You're probably on an older version which has since been fixed.
It looks like this was fixed 4 months ago:
It'll get pushed to STM32CubeMX files whenever they make a new release.
2026-03-01 3:52 PM
> OB->WRP0 |= WRP0_Data;
> OB->WRP1 |= WRP1_Data;
> OB->WRP2 |= WRP2_Data;
> OB->WRP3 |= WRP3_Data;
These lines don't appear in the latest stm32f1xx_hal_flash_ex.c file:
You're probably on an older version which has since been fixed.
It looks like this was fixed 4 months ago:
It'll get pushed to STM32CubeMX files whenever they make a new release.
2026-03-01 11:10 PM
You're right, I was in fact using an older version. Thanks.