The STM32 Flash information block section contains special option bytes that can be used for information such as system configuration, as well as user-defined data bytes for two valid bytes (actual four bytes, two are check bytes).
When I tried to write the user custom byte, I encountered a write error, compared to the user manual, the steps of the application have been completed.
Later, by comparing the Flash related examples in the example of the system library, we can see the correct way of writing, and also include "Erase" and "copy" and "write" to the original inform code as follows.
HAL_FLASH_Unlock();
HAL_FLASH_OB_Unlock();
FLASH_OBProgramInitTypeDef obData;
HAL_FLASHEx_OBGetConfig(&obData);
HAL_FLASHEx_OBErase();
obData.DATAAddress = OB_DATA_ADDRESS_DATA0;
obData.DATAData = 0xAE; //Custom data
obData.OptionType = OPTIONBYTE_DATA;
if ((ret = HAL_FLASHEx_OBProgram(&obData)) != HAL_OK){
extern FLASH_ProcessTypeDef pFlash;
char tmp[50] = {0};
sprintf(tmp, "write optby fail for %x, %08x", ret, pFlash.ErrorCode);
debug(tmp, strlen(tmp));
return -1;
}
obData.DATAAddress = OB_DATA_ADDRESS_DATA1;
obData.DATAData = 0xC9; //Custom data
if ((ret = HAL_FLASHEx_OBProgram(&obData)) != HAL_OK){
char tmp[50] = {0};
sprintf(tmp, "write optby fail for %x", ret);
debug(tmp, strlen(tmp));
return -1;
}
Of course, tools can also be used for more convenience.
Like Mcpisp.
STM32 Write options Byte (option bytes) for correct posture