cancel
Showing results for 
Search instead for 
Did you mean: 

Error while flashing.

Vibhanshu5396
Visitor

I am flashing a code to write into the last sector of the flash memory of STM32F401 Nucleo Board, for the first time the code was successfully dumped into the flash but while dumping it the second time this error pops up, whenever i mass erase the whole flash it again works properly but the second it doesn't. I even tried using different sectors but the issue was still there.

What might be a possible solution of this error.

I am attaching the snapshot of the error and the code snippet as well.

Screenshot 2025-11-17 150755.png

uint32_t Flash_Write_Data (uint32_t StartSectorAddress, uint32_t *Data, uint16_t numberofwords)
{
static FLASH_EraseInitTypeDef EraseInitStruct;
uint32_t SECTORError;
int sofar=0;

/* Unlock the Flash to enable the flash control register access *************/
  HAL_FLASH_Unlock();

  /* Erase the user Flash area */
  /* Get the number of sector to erase from 1st sector */
  uint32_t StartSector = GetSector(StartSectorAddress);
  uint32_t EndSectorAddress = StartSectorAddress + numberofwords*4;
  uint32_t EndSector = GetSector(EndSectorAddress);

  /* Fill EraseInit structure*/
  EraseInitStruct.TypeErase     = FLASH_TYPEERASE_SECTORS;
  EraseInitStruct.VoltageRange  = FLASH_VOLTAGE_RANGE_3;
  EraseInitStruct.Sector        = StartSector;
  EraseInitStruct.NbSectors     = (EndSector - StartSector) + 1;

  /* Note: If an erase operation in Flash memory also concerns data in the data or instruction cache,
     you have to make sure that these data are rewritten before they are accessed during code
     execution. If this cannot be done safely, it is recommended to flush the caches by setting the
     DCRST and ICRST bits in the FLASH_CR register. */
  if (HAL_FLASHEx_Erase(&EraseInitStruct, &SECTORError) != HAL_OK)
  {
  return HAL_FLASH_GetError ();
  }

  /* Program the user Flash area word by word
    (area defined by FLASH_USER_START_ADDR and FLASH_USER_END_ADDR) ***********/

   while (sofar<numberofwords)
   {
     if (HAL_FLASH_Program(FLASH_TYPEPROGRAM_WORD, StartSectorAddress, Data[sofar]) == HAL_OK)
     {
    StartSectorAddress += 4;  // use StartPageAddress += 2 for half word and 8 for double word
    sofar++;
     }
     else
     {
       /* Error occurred while writing data in Flash memory*/
    return HAL_FLASH_GetError ();
     }
   }

  /* Lock the Flash to disable the flash control register access (recommended
     to protect the FLASH memory against possible unwanted operation) *********/
  HAL_FLASH_Lock();

   return 0;
}

Edited to apply source code formatting - please see How to insert source code for future reference.

0 REPLIES 0