2022-02-05 08:54 AM
Hello all,
Can anyone in his forum to let me know whether can be write a byte in to the flash memory of the STM32F030CC uC, it always asking to increment the the write size as '4' bytes, if I hchange the code to write as a byte or even a two bytes the uC enter into hard fault handler, why? The code is below:
uint32_t Flash_Write_Data (uint32_t StartPageAddress, uint32_t *Data, uint16_t numberofwords)
{
static FLASH_EraseInitTypeDef EraseInitStruct;
uint32_t PAGEError;
int sofar = 0;
/* Unlock the Flash to enable the flash control register access *************/
HAL_FLASH_Unlock();
/* Erase the user Flash area*/
uint32_t StartPage = GetPage(StartPageAddress);
uint32_t EndPageAdress = StartPageAddress + numberofwords*4;
uint32_t EndPage = GetPage(EndPageAdress);
/* Fill EraseInit structure*/
EraseInitStruct.TypeErase = FLASH_TYPEERASE_PAGES;
EraseInitStruct.PageAddress = StartPage;
EraseInitStruct.NbPages = ((EndPage - StartPage)/FLASH_PAGE_SIZE) +1;
if (HAL_FLASHEx_Erase(&EraseInitStruct, &PAGEError) != HAL_OK)
{
/*Error occurred while page erase.*/
return HAL_FLASH_GetError ();
}
/* Program the user Flash area word by word*/
while (sofar < numberofwords)
{
if (HAL_FLASH_Program(FLASH_TYPEPROGRAM_WORD, StartPageAddress, Data[sofar]) == HAL_OK)
{
StartPageAddress += 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;
}
2022-02-05 09:33 AM
The reference manual says:
"The main Flash memory can be programmed 16 bits at a time. The program operation is started when the CPU writes a half-word into a main Flash memory address with the PG bit of the FLASH_CR register set. Any attempt to write data that are not half-word long will result in a bus error generating a Hard Fault interrupt."
Programming 16 Bits work if you use FLASH_TYPEPROGRAM_HALFWORD in your above code.
If you have to write several small pieces of data repeatedly, you might want to look into eeprom emulation code.
hth
KnarfB
2022-02-05 09:38 AM
Cortex-M0 will fault if you do unaligned reads or writes.
`Write structures as blocks of words, or come up with a different strategy to write/journal data into Flash sector(s)