AnsweredAssumed Answered

Writing/Reading to flash

Question asked by Phataas on Feb 2, 2014
Latest reply on Feb 3, 2014 by Phataas
I have read the ST Flash programming manual and looked at the ST examples. I am using STM32F103VC.

I wrote some code to initialize and write/read from flash memory. This is just a test, but I end up in the hard fault handler so I must be accessing an invalid memory location or something.

When debugging I can see that the flash is written in memory. So I think it might be the read function causing this?

flash.c:

#define FLASH_PAGE_SIZE         ((uint16_t) 0x800)
#define BANK1_WRITE_START_ADDR  ((uint32_t) 0x08008000)
#define PAGES_TO_ERASE          2
  
static FLASH_Status flashStatus;
static uint32_t currentAddress = BANK1_WRITE_START_ADDR + 4;
  
bool_t Flash_Initialize(void)
{
    uint8_t i;
  
    //Unlock flash bank 1.
    FLASH_UnlockBank1();
  
    //Clear pending flags.
    FLASH_ClearFlag(FLASH_FLAG_EOP | FLASH_FLAG_PGERR | FLASH_FLAG_WRPRTERR);
  
    for(i = 0; i < PAGES_TO_ERASE; i++)
    {
        flashStatus = FLASH_ErasePage(BANK1_WRITE_START_ADDR + (FLASH_PAGE_SIZE * i));
        if(flashStatus != FLASH_COMPLETE)
        {
//          FLASH_LockBank1();
            return FALSE;
        }
    }
  
//  FLASH_LockBank1();
    return TRUE;
}
  
bool_t Flash_Write(uint32_t data)
{
//  FLASH_UnlockBank1();
    flashStatus = FLASH_ProgramWord(currentAddress, data);
//  FLASH_LockBank1();
    currentAddress += 4;
    if(flashStatus != FLASH_COMPLETE) return FALSE;
    if(Flash_Read( (currentAddress - 4) ) != data) return FALSE;
    return TRUE;
}
  
uint32_t Flash_Read(uint32_t address)
{
    return (*(volatile uint32_t*) address);
}

main.c:

status = Flash_Initialize();
if(status)
{
    DEBUG("Flash initialize OK");
}
else
{
    DEBUG("Flash initialize FAILED");
}
status = Flash_Write(0xAAAAAAAA);
if(status)
{
    data = Flash_Read(0x08008000);
    DEBUG("Flash write and read back OK: %u\n", data);
}
else
{
    data = Flash_Read(0x08008000);
    DEBUG("Flash write and read back FAILED: %u\n", data);
}

Outcomes