cancel
Showing results for 
Search instead for 
Did you mean: 

Flash erase operation fail CMSIS STM32L4

ngrigoriadis
Senior

Hello,

I am trying to implement a flash erase function, which is based on the reference manual. I am using the STM32L476RG nucleo board. From there the instructions are: 

To erase a page (2 Kbyte), follow the procedure below:

  1.  Check that no Flash memory operation is ongoing by checking the BSY bit in the Flash
    status register (FLASH_SR).
  2. Check and clear all error programming flags due to a previous programming. If not,
    PGSERR is set.
  3.  Set the PER bit and select the page you wish to erase (PNB) with the associated bank
    (BKER) in the Flash control register (FLASH_CR).
  4. Set the STRT bit in the FLASH_CR register.
  5. Wait for the BSY bit to be cleared in the FLASH_SR registe

So for that operation I have created a function based on CMSIS which is the following: 

 

uint16_t bl_flash_page_erase(uint32_t page, uint16_t bank)
{
	/*Wait if any flash memory operation is ongoing*/
	while (READ_BIT(FLASH->SR, FLASH_SR_BSY)) {}

	/*Check if any error occurs due to previous programming*/
	bl_flash_clear_status_flags();

	/*Check the bank of flash memory, specified by the user*/
	if (bank == 1) {
		/*Set bank 1*/
		CLEAR_BIT(FLASH->CR, FLASH_CR_BKER);
	} else if (bank == 2) {
		/*Set bank 2*/
		SET_BIT(FLASH->CR, FLASH_CR_BKER);
	} else {
		/*Undefined bank space*/
		return 0;
	}

	/*Define the page that must be erased*/
	MODIFY_REG(FLASH->CR, FLASH_CR_PNB, (page << FLASH_CR_PNB_Pos));

	/*Enable page erase operation*/
	SET_BIT(FLASH->CR, FLASH_CR_PER);

	/*Start the procedure*/
	SET_BIT(FLASH->CR, FLASH_CR_STRT);

	/*Wait the flash to finish its ongoing operation*/
	while (READ_BIT(FLASH->SR, FLASH_SR_BSY)) {}

	/*Disable page operation*/
	CLEAR_BIT(FLASH->CR, FLASH_CR_PER);

	return 1;
}

 

The thing is that it is doesn't turn on the START bit and the erase operation never happens. I have tried to change the position of this operation (SET STRT bit) and put it at the begging, then it manages to turn it on however the system crashes. What am I doing wrong here? 

 

1 ACCEPTED SOLUTION

Accepted Solutions
LCE
Principal

Have you unlocked flash access by writing the key registers?

Check LOCK bit 31 in CR.

View solution in original post

3 REPLIES 3
Saket_Om
ST Employee

Hello @ngrigoriadis 

 

To implement your function, you can refer to the function FLASH_PageErase() available in stm32l4xx_hal_flash_ex.c

 

 

If your question is answered, please close this topic by clicking "Accept as Solution".

Thanks
Omar
LCE
Principal

Have you unlocked flash access by writing the key registers?

Check LOCK bit 31 in CR.

That was the issue thank you very much!