cancel
Showing results for 
Search instead for 
Did you mean: 

STM32L412CB Flash Write/Erase fails first time only, then works OK.

DBhut.1
Senior
uint32_t write_to_flash(uint8_t * buf, uint16_t length){
	if((length)>2047) return 0xFFFFFFFF;
	uint32_t base_addr=0;
	base_addr=getHexAddressPage(DATA_PAGE);
 
	uint32_t PAGEError;
 
  /* Unlock the Flash to enable the flash control register access *************/
	HAL_FLASH_Unlock();
	__HAL_FLASH_CLEAR_FLAG(FLASH_FLAG_EOP | FLASH_FLAG_OPERR | FLASH_FLAG_PROGERR | FLASH_FLAG_WRPERR | FLASH_FLAG_PGAERR |
	  FLASH_FLAG_SIZERR | FLASH_FLAG_PGSERR | FLASH_FLAG_MISERR | FLASH_FLAG_FASTERR | FLASH_FLAG_OPTVERR);
	  __HAL_FLASH_CLEAR_FLAG(FLASH_FLAG_ALL_ERRORS);
   /* Erase the user Flash area*/
 
   /* Fill EraseInit structure*/
   EraseInitStruct.TypeErase= FLASH_TYPEERASE_PAGES;
   EraseInitStruct.Page = DATA_PAGE;
   EraseInitStruct.NbPages= 1;
 
   if (HAL_FLASHEx_Erase(&EraseInitStruct, &PAGEError) != HAL_OK)
   {
	   DBGx("Flash Erase Fail\r\n");
		 HAL_FLASH_Lock();
	   return HAL_FLASH_GetError();
   }
 
	 for (uint32_t i = 0; i < length; i += 8)
	 {
	    uint64_t data64 = u8touint64(buf+i);
	    PAGEError=HAL_FLASH_Program(FLASH_TYPEPROGRAM_DOUBLEWORD, i + base_addr, data64);
	    if (PAGEError != HAL_OK)
	    {
	      HAL_FLASH_Lock();
	      DBGx("2 IS_FLASH_PAGE(Page):%d at mem:%x,PAGEError:%x\r\n",IS_FLASH_PAGE(DATA_PAGE),DATA_PAGE,PAGEError);
	      return PAGEError;
	    }
	 }
 
	HAL_FLASH_Lock();
	DBGx("Flash Error:%d\r\n",PAGEError);
	return PAGEError;
}

Above code is used to write flash

12 REPLIES 12

Sorry, I didn't get your point, can you please elaborate more on this.

which error bit I am not clearing?

@Community member​  Please can you elaborate more on "There's another error bit you're not clearing."

The hypothesis here being that if you print it out, and share that, we might collectively better understand what's actually reported as failing. This generally works better than guessing in these situations.

You clear many error bits, but probably not all.

Tips, Buy me a coffee, or three.. PayPal Venmo
Up vote any posts that you find helpful, it shows what's working..