why can't program FLASH when FLASH all bit is 1?
I use STM32L431, it only possible to program double word, I want program a new data to FLASH if the 64 bits all is '1' in FLASH, otherwise, if the 64 bits is not all '1', I erase it first before program. But when I program a 0xffffffffffffffff to the 64 bits and then need to program a new data(for example: 0x1122334455667788), it fail to program.
void Flash_Test(void)
{
uint32_t startAddr = 0x0801C000;
HAL_StatusTypeDef status;
FLASH_EraseInitTypeDef EraseInitStruct;
uint32_t pageErr;
printf("erase one page\r\n");
/*erase one page*/
HAL_FLASH_Unlock();
__HAL_FLASH_CLEAR_FLAG(FLASH_FLAG_OPTVERR);
EraseInitStruct.TypeErase = FLASH_TYPEERASE_PAGES;
EraseInitStruct.Banks = GetBank(startAddr);
EraseInitStruct.Page = GetPage(startAddr);
EraseInitStruct.NbPages = 1;
status = HAL_FLASHEx_Erase(&EraseInitStruct, &pageErr);
HAL_FLASH_Lock();
if (status != HAL_OK)
return;
printf("before write 0xff to one page\r\n");
for (int i = 0; i < 2048; i += 4)
{
printf("%x ", *(volatile uint32_t*)(startAddr + i));
}
printf("\r\n");
/*write 0xff to one page*/
HAL_FLASH_Unlock();
__HAL_FLASH_CLEAR_FLAG(FLASH_FLAG_OPTVERR);
for (int i = 0; i < 2048; i += 8)
{
status = HAL_FLASH_Program(FLASH_TYPEPROGRAM_DOUBLEWORD, startAddr + i, 0xffffffffffffffff);
if (status != HAL_OK)
{
printf("Fail to write all pages!\r\n");
break;
}
}
HAL_FLASH_Lock();
printf("after write 0xff to one page\r\n");
for (int i = 0; i < 2048; i += 4)
{
printf("%x ", *(volatile uint32_t*)(startAddr + i));
}
printf("\r\n");
printf("write 0xff\r\n");
/*write 8 bytes*/
HAL_FLASH_Unlock();
__HAL_FLASH_CLEAR_FLAG(FLASH_FLAG_OPTVERR);
status = HAL_FLASH_Program(FLASH_TYPEPROGRAM_DOUBLEWORD, startAddr, 0xffffffffffffffff);
if (status != HAL_OK)
{
printf("Fail to write 8 bytes!\r\n");
}
HAL_FLASH_Lock();
}
Run this sample code, it will print "Fail to write 8 bytes".
Possible to program 1 to 0 and can't program 0 to 1 is FLASH's feature. In this case, even if all the bits is '1' in FLASH, HAL_FLASH_Program still return HAL_ERROR. Why?
Thanks!
