cancel
Showing results for 
Search instead for 
Did you mean: 

Writing/Reading to flash

patrickbrataas9
Associate II
Posted on February 02, 2014 at 18:20

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);

}

2 REPLIES 2
Posted on February 03, 2014 at 01:10

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.

The magical thing about a Hard Fault is that if you have a reasonable handler, you could actually make a pretty conclusive diagnosis instead of a random stab in the dark.

The code itself doesn't appear too bad, are you perhaps erasing a section of memory with code residing in it?
Tips, Buy me a coffee, or three.. PayPal Venmo
Up vote any posts that you find helpful, it shows what's working..
patrickbrataas9
Associate II
Posted on February 03, 2014 at 01:51

It looks like I did. I changed the

BANK1_WRITE_START_ADDR

to 0x0804 0000 which is in the middle of my flash and it solved this problem. My program size was 0x15C34 so I was overwriting parts of the code...