Skip to main content
Graduate
January 31, 2025
Solved

Overwriting Internal flash after erasing previous data doesn't work

  • January 31, 2025
  • 2 replies
  • 1204 views

Hi 

I was trying to store the status of certain pins on flash memory so that I can read from flash and resume after power cycle, I have successfully written data in flash memory, I chose the last page starting address to store my data. 

Meghana_0-1738324263612.png

void write_array_to_flash(uint8_t* data, uint32_t size) {
 check_write_protection(STATUS_ARRAY_ADDRESS);
 HAL_FLASH_Unlock();
 // Erase the sector before writing (if necessary)
 FLASH_EraseInitTypeDef eraseInitStruct;
 uint32_t pageError = 0;
 eraseInitStruct.TypeErase = FLASH_TYPEERASE_PAGES;
 eraseInitStruct.Page = (STATUS_ARRAY_ADDRESS - FLASH_BASE) / FLASH_PAGE_SIZE;
 eraseInitStruct.NbPages = 1;
 if (HAL_FLASHEx_Erase(&eraseInitStruct, &pageError) != HAL_OK) {
 // Handle error
 HAL_FLASH_Lock();
 return;
 }
 // Write the array to flash
 uint64_t data_quadword[2] = {0xFFFFFFFFFFFFFFFF, 0xFFFFFFFFFFFFFFFF};
 memcpy(data_quadword, data, size);

 // Ensure the address is aligned for a quad word write
 if ((STATUS_ARRAY_ADDRESS % 16) != 0) {
 // Handle error
 HAL_FLASH_Lock();
 return;
 }
 HAL_FLASH_Program(FLASH_TYPEPROGRAM_QUADWORD, STATUS_ARRAY_ADDRESS, (uint32_t)data_quadword);

 HAL_FLASH_Lock();
}

But when trying to overwrite data after erasing it is not happening, when observed in debug state, the memory sector is not under write protection, when erase function HAL_FLASHEx_Erase(&eraseInitStruct, &pageError)  is called it returns HAL_OK but when memory segment observed, the data in that memory segment did not become all 1's, later when HAL_FLASH_Program(FLASH_TYPEPROGRAM_QUADWORD, STATUS_ARRAY_ADDRESS, (uint32_t)data_quadword) is called not data change is observed.

I've attached the main.c file below. Let me know where I'm going wrong.
Thankyou.

    This topic has been closed for replies.
    Best answer by TDK

    The Banks value is invalid. Probably should be FLASH_BANK_1.

    2 replies

    Super User
    January 31, 2025

    @Meghana wrote:

    But when trying to overwrite data after erasing it is not happening, .


    Are you sure the erase is actually happening?

    MeghanaAuthor
    Graduate
    January 31, 2025

    Hi @Andrew Neil  
    Erase is not happening when checked in debug mode, all the bits should become 1 that's not happening but it is returning status is HAL_OK.

    Super User
    January 31, 2025

    Show the content of eraseInitStruct when HAL_FLASHEx_Erase is called.

    Show the value of STATUS_ARRAY_ADDRESS.

    MeghanaAuthor
    Graduate
    January 31, 2025

    Hi @TDK 

    Meghana_1-1738331454151.png

    I have attached the ss above after doing stepover also the contents of eraseInitStruct didn't change.

     

    TDKAnswer
    Super User
    January 31, 2025

    The Banks value is invalid. Probably should be FLASH_BANK_1.