arry_h
arry_h

Reputation: 167

Understanding the writing to flash process in the STM32 reference manual

I am programming the stm32l412kb where at one point I will be writing data to flash (from UART). From the stm32l41xx reference manual, I understand the steps in how to clear the memory before writing to it but on page 84 there is one step that I do not know how to do when writing the actual data. That step is the

Perform the data write operation at the desired memory address

What data write operation is it mentioning? I can't see any register the memory address goes to so I assume its going to use pointers? How would I go about doing this?

Your help is much appreciated, Many thanks,

Harry

Upvotes: 3

Views: 5966

Answers (2)

KamilCuk
KamilCuk

Reputation: 140880

What data write operation is it mentioning?

The "data write" is just a normal write to a address in memory that is the flash memory. It is usually the STR assembly instruction. Screening at your datasheet, I guess the flash memory addresses are between 0x08080000 and 0x00080000.

Ex. the following C code would write the value 42 to the first flash memory address:

 *(volatile uint32_t*)0x00080000 = 42.

For a reference implementation you can see stm32 hal drivers:

  /* Set PG bit */
  SET_BIT(FLASH->CR, FLASH_CR_PG);

  /* Program the double word */
  *(__IO uint32_t*)Address = (uint32_t)Data;
  *(__IO uint32_t*)(Address+4) = (uint32_t)(Data >> 32);

Upvotes: 3

Vinci
Vinci

Reputation: 1510

Apart from a couple of things (e.g. only write after erase, timings, alignment, lock/unlock) their ain't much difference between writing to RAM and writing to FLASH memory. So if you have followed the steps from the reference manual and the FLASH memory is ready (i.e. cleared and unlocked) then you can simply take an aligned memory address and write to it.

STMs very own HAL library contains a function which does all the cumbersome boilerplate for you and allows you to "just write":

HAL_StatusTypeDef HAL_FLASH_Program(uint32_t TypeProgram, uint32_t Address, uint64_t Data)

Internally this function uses a subroutine which performs the actual write and it looks like this:

static void FLASH_Program_DoubleWord(uint32_t Address, uint64_t Data)
{
  /* Check the parameters */
  assert_param(IS_FLASH_PROGRAM_ADDRESS(Address));

  /* Set PG bit */
  SET_BIT(FLASH->CR, FLASH_CR_PG);

  /* Program first word */
  *(__IO uint32_t*)Address = (uint32_t)Data;

  /* Barrier to ensure programming is performed in 2 steps, in right order
    (independently of compiler optimization behavior) */
  __ISB();

  /* Program second word */
  *(__IO uint32_t*)(Address+4U) = (uint32_t)(Data >> 32);
}

As you can see there is no magic involved. It's just a dereferenced pointer and an assignment.

Upvotes: 7

Related Questions