7

So I can't write to internal flash memory directly after erasing it. If there's no erase operation before write operation, then I can. Any ideas as to why?

Programming function returns 'successful write' value, but when looking at memory, no data is written. Here's the code:

uint32_t pageAddress = 0x08008000;
uint16_t buffer = 0xAAAA;

HAL_FLASH_Unlock();
FLASH_PageErase(pageAddress);
HAL_FLASH_Program(TYPEPROGRAM_HALFWORD, pageAddress, buffer);
HAL_FLASH_Lock();

I've tried locking the memory between erasing and programming it, creating a delay between these operations, that doesn't help.

divibisan
  • 11,659
  • 11
  • 40
  • 58
andrey
  • 1,515
  • 5
  • 23
  • 39

2 Answers2

13

The problem was that PER bit in FLASH->CR register which is set when FLASH_PageErase() is called isn't cleared at the end of it. Clearing this bit while flash is still unlocked allows other operations on flash to be run after that.

STM documentation has nothing to say about this.

andrey
  • 1,515
  • 5
  • 23
  • 39
  • 1
    You saved my day. Another thing I noticed is, that when you try to perform few consecutive stores (using `HAL_FLASH_Program`) you have to clear PG bit after each operation (at least that was my case on STM32F072). So I modified my program so it performs `CLEAR_BIT (FLASH->CR, (FLASH_CR_PER))` after page clear and `CLEAR_BIT (FLASH->CR, (FLASH_CR_PG))` after programming a word. – iwasz Jun 22 '17 at 13:27
  • i wanted to erase a page and i called FLASH_pageErase (pageaddress) but after erasing I'm not able to burn code into ST.Its showing"internal command Error" and "Flash download failed " what may be the issue? –  Dec 03 '17 at 09:33
  • Load "abc\\abc.axf" Error: Flash Download failed - Target DLL has been cancelled Flash Load finished at 15:08:10 Load "abc\\abc.axf" Error: Flash Download failed - Target DLL has been cancelled Flash Load finished at 15:08:18 –  Dec 03 '17 at 09:39
  • OMG. You saved my day, an incorrect AND! My code was |= !PER, instead |= ~PER. Damn! Thanks a bunch. – 0x3333 Mar 11 '19 at 02:53
  • :) this was great help for me. THANK YOU – Jeroen Lammertink Dec 20 '22 at 19:03
0

You can use HAL_FLASHEx_Erase instead.

uint32_t pageAddress = 0x0801FC00;
FLASH_EraseInitTypeDef EraseInitStruct;
uint32_t page_err;

EraseInitStruct.TypeErase = FLASH_TYPEERASE_PAGES;
EraseInitStruct.PageAddress = pageAddress;
EraseInitStruct.NbPages = 1;

uint32_t buffer = 0xC0FFEE;
HAL_FLASH_Unlock();
HAL_FLASHEx_Erase(&EraseInitStruct, &page_err);
HAL_FLASH_Program(FLASH_TYPEPROGRAM_WORD, pageAddress, buffer);
HAL_FLASH_Lock();
Creek Drop
  • 464
  • 3
  • 13