I have been working with the STM32F407. When the device is flashed for the first time, I manually write some very important information to flash memory. I use the following function to write to the flash memory:
#define SERIAL_OFFSET 0x80E0000
void FLASH_write_serial_number(uint32_t serial_number) {
taskENTER_CRITICAL();
uint32_t write_test = serial_number;
HAL_FLASH_Unlock();
FLASH_WaitForLastOperation(2000);
if(HAL_FLASH_Program(FLASH_TYPEPROGRAM_WORD, SERIAL_OFFSET, write_test) == HAL_OK){
printf("FLASH_WRITE_OK\n");
}
else{
printf("FLASH_WRITE_FAIL\n");
}
FLASH_WaitForLastOperation(2000);
HAL_FLASH_Lock();
FLASH_WaitForLastOperation(2000);
taskEXIT_CRITICAL();
}
I noticed that sometimes the data dissapears from the flash memory. Reading back from it returns: 4294967295 Which means that is clear.
In order to ensure the data does not dissapear from the flash memory, I decided to activate write protection for the whole sector that I use (sector 11). I do this via STM32CubeProgrammer:
That seemed to fix my problem and the data no longer dissapears. However, it is very inconvenient to run STM32CubeProgrammer for each device and disable that checkbox. I was hoping if there is an easier way to achieve the same results from the code. Is there a function that would allow me to activate write protection for a particular section? I have tried looking up online but didint manage to find any results
