It has worked at times but at others is becoming all 0xFFFF or whatever values become written into unused areas.
Currently it loses memory every time.
My code reads a block of settings and looks at one location to check if it's zero, which indicates no 'priming' of the settings is required. If not zero the settings are primed with default values with that bit cleared to zero. All locations are written to in the block, zero if not used. They are uint64_t values. Changes to settings all include that bit as zero, so the priming won't occur again. But on each startup that location is above zero.
I've tried adding __NOP() lines and delays immediately after writing also.
While the device is operating the settings are saved, but at power down they become overwritten.
The flash writing code is
void WriteSettings(void){
HAL_FLASH_Unlock();
FirstPage = GetPage(FLASH_USER_START_ADDR);
NbOfPages = GetPage(FLASH_USER_END_ADDR) - FirstPage + 1; /* Get the number of pages to erase from 1st page */
BankNumber = GetBank(FLASH_USER_START_ADDR); /* Get the bank */
EraseInitStruct.TypeErase = FLASH_TYPEERASE_PAGES; EraseInitStruct.Banks = BankNumber;
EraseInitStruct.Page = FirstPage; EraseInitStruct.NbPages = NbOfPages;
if (HAL_FLASHEx_Erase(&EraseInitStruct, &PAGEError) != HAL_OK)
{while (1){HAL_Delay(100); __NOP(); HAL_Delay(2000);}}// Error occurred while page erase.
Address = FLASH_USER_START_ADDR;//PROGRAM THE FLASH WORD BY WORD
while (Address < FLASH_USER_END_ADDR)
{//HERE WRITE SPECIFIC DATA
if(!CG_FlashCount){
for(CG_FlashCount = 0; CG_FlashCount<(sizeof(CG_FlashItem))>>3; CG_FlashCount++){
if(HAL_FLASH_Program(FLASH_TYPEPROGRAM_DOUBLEWORD, Address, CG_FlashItem[CG_FlashCount]) == HAL_OK){Address = Address + 8;}else{ while (1){ HAL_Delay(100);__NOP();HAL_Delay(2000);}}}
}
//NOW THE REMAINING FLASH AREA
if (HAL_FLASH_Program(FLASH_TYPEPROGRAM_DOUBLEWORD, Address, DATA_64) == HAL_OK){Address = Address + 8;}else{ while (1){ HAL_Delay(100);__NOP();HAL_Delay(2000);}}}/* Error occurred while writing data in Flash memory. User can add here some code to deal with this error */
HAL_FLASH_Lock();/* Lock the Flash to disable the flash control register access (recommended to protect the FLASH memory against possible unwanted operation) *********/
}