2025-02-24 05:04 AM
Hi
We are facing problems when reading a data that is written to the flash using the following function?
Every time we write in reading the data the micro-controller crashes. Even if I want to see the content of the flash in that particular address using STM32Programmer, it throughs an error.
// Function to write structure to Flash
void Flash_WriteStruct(uint32_t address, struct DeviceData* data)
{
FLASH_EraseInitTypeDef EraseInitStruct;
uint32_t PageError = 0;
// Erase the flash page (for example, page 2 at 0x08000200)
EraseInitStruct.TypeErase = FLASH_TYPEERASE_SECTORS;
EraseInitStruct.Banks = FLASH_BANK_1; // Address of page 2
EraseInitStruct.NbSectors = 1;
EraseInitStruct.Sector = FLASH_SECTOR_2; // Number of pages to erase
EraseInitStruct.VoltageRange = FLASH_VOLTAGE_RANGE_3;
// Disable interrupts before starting the flash write
__disable_irq();
SCB_DisableICache();
HAL_FLASH_Unlock();
if (HAL_FLASHEx_Erase(&EraseInitStruct, &PageError) != HAL_OK) {
// Handle error
__NOP();
}
else
{
// Calculate the structure size in bytes
uint16_t dataSize = sizeof(struct DeviceData);
uint8_t buffer[32] = {0}; // Temporary buffer for 32-byte alignment
for (uint16_t i = 0; i < dataSize; i+=32)
{
memset(buffer, 0xFF, 32); // Flash default value after erase
memcpy(buffer, ((uint8_t*)data) + i, (dataSize - i > 32) ? 32 : (dataSize - i));
//uint8_t byte = *((uint8_t*)(data) + i);
//HAL_FLASHEx_DATAEEPROM_Program(FLASH_TYPEPROGRAMDATA_BYTE, address + i, byte); // Write each byte of data to the EEPROM
//HAL_FLASH_Program(FLASH_TYPEPROGRAM_FLASHWORD, address + i, byte);
if (HAL_FLASH_Program(FLASH_TYPEPROGRAM_FLASHWORD, address + i, (uint32_t)buffer) != HAL_OK) {
// Handle programming error
HAL_FLASH_Lock();
/* Enable instruction cache prior to internal cacheable memory update */
SCB_EnableICache();
// Re-enable interrupts after the write
__enable_irq();
return;
}
}
}
HAL_FLASH_Lock(); // Lock the EEPROM
/* Enable instruction cache prior to internal cacheable memory update */
SCB_EnableICache();
// Re-enable interrupts after the write
__enable_irq();
}
// Function to read structure from Flash
void Flash_ReadStruct(uint32_t address, struct DeviceData* data)
{
// Calculate the structure size in bytes
uint16_t dataSize = sizeof(struct DeviceData);
for (uint16_t i = 0; i < dataSize; i++)
{
*((uint8_t*)(data) + i) = *(uint8_t*)(address + i); // Read each byte of data from the EEPROM
}
}
2025-02-24 06:07 AM
So Flash_ReadStruct is producing a hardf fault? Set a breakpoint and show the values of the arguments you're using when you call it. Probably a bad pointer.
2025-02-24 08:00 AM - edited 2025-02-24 08:06 AM
Hi
Thanks for you reply. I will do this. Can you please just explain what you meant by bad pointer?
I need to also mention that some time the data is read correctly and sometimes the read operation crashes the uC.
Regards,
Pej