HardFault when i try to program in the Flash memory
Hello,
I need to write data in the flash memory but i always have a hard fault !
please check my code if some one can find the Issus !
(i written my own functions because i do not use hal library)
void FLASH_Write_64(uint32_t WriteAddr, uint64_t *data, uint16_t NumToWrite)
{
uint16_t write_index = 0;
//Unlock the Flash to enable the flash control register access
FLASH_IF_Unlock();
//calculate the user Flash area
uint32_t StartPage = FLASH_IF_GetPage(WriteAddr);
uint32_t EndPageAdress = WriteAddr + NumToWrite*8;
uint32_t EndPage = FLASH_IF_GetPage(EndPageAdress);
//Erase the user Flash area
FLASH_IF_Erase(StartPage, (EndPage - StartPage +1));
//Program the user Flash area word by word
while(write_index < NumToWrite)
{
FLASH_IF_Program(WriteAddr, data[write_index]);
WriteAddr += 8;
write_index++;
}
//Lock the Flash to disable the flash control register access (recommended
//to protect the FLASH memory against possible unwanted operation)
FLASH_IF_Lock();
}
void FLASH_IF_Erase(uint32_t FirstPage, uint32_t NbrOfPage)
{
uint32_t index;
//Verify that next operation can be proceed
FLASH_IF_WaitForLastOperation();
for (index = FirstPage; index < (FirstPage + NbrOfPage); index++)
{
//Start erase page
FLASH_IF_PageErase(index);
//Wait for last operation to be completed
FLASH_IF_WaitForLastOperation();
}
}
static void FLASH_IF_PageErase(uint32_t Page)
{
//Proceed to erase the page
#ifdef CORE_CM0PLUS
MODIFY_REG(FLASH->C2CR, FLASH_CR_PNB, ((Page << FLASH_CR_PNB_Pos) | FLASH_CR_PER | FLASH_CR_STRT));
#else
MODIFY_REG(FLASH->CR, FLASH_CR_PNB, ((Page << FLASH_CR_PNB_Pos) | FLASH_CR_PER | FLASH_CR_STRT));
#endif
}
void FLASH_IF_Program(uint32_t Address, uint64_t Data)
{
//Verify that next operation can be proceed
FLASH_IF_WaitForLastOperation();
//Program double-word (64-bit) at a specified address
FLASH_IF_Program_DoubleWord(Address, Data);
//Wait for last operation to be completed
FLASH_IF_WaitForLastOperation();
//If the program operation is completed, disable the PG or FSTPG Bit
#ifdef CORE_CM0PLUS
CLEAR_BIT(FLASH->C2CR, FLASH_CR_PG);
#else
CLEAR_BIT(FLASH->CR, FLASH_CR_PG);
#endif
}
static void FLASH_IF_Program_DoubleWord(uint32_t Address, uint64_t Data)
{
#ifdef CORE_CM0PLUS
//Set PG bit
SET_BIT(FLASH->C2CR, FLASH_CR_PG);
#else
//Set PG bit
SET_BIT(FLASH->CR, FLASH_CR_PG);
#endif
//Program first word
*(uint32_t *)Address = (uint32_t)Data;
__ISB();
//Program second word
*(uint32_t *)(Address + 4U) = (uint32_t)(Data >> 32U);
}