1

I am trying to store the data inside the Flash (non volatile memory) for further retrieve. So that when the power is off and on again , then I can read the data from memory.

uint32_t address = 0x0800C000;
uint64_t data = 0x01;
HAL_FLASH_Unlock();
HAL_FLASH_Program(TYPEPROGRAM_WORD, address, data);
HAL_FLASH_Lock();

But I am not able to store the data at this location, I dont know why?? And is there any function to read the data back from this location in HAL??

akmozo
  • 9,829
  • 3
  • 28
  • 44
Aashram
  • 13
  • 1
  • 6
  • See also [Allocating memory in Flash for user data (STM32F4 HAL)](https://stackoverflow.com/a/28505272/1398841) – phoenix Sep 24 '18 at 19:44

1 Answers1

0

You have to erase Flash first, then you can write new data

/*
* write data to internal flash
* return: value if OK, 0 if Error
*/
uint32_t WriteToFlash(uint32_t address, uint32_t value)
{
    uint32_t PAGEError = 0;
    uint32_t result = 0;

    /* Unlock the Flash to enable the flash control register access *************/
    HAL_FLASH_Unlock();

    /* Erase the user Flash area */
    EraseInitStruct.TypeErase   = FLASH_TYPEERASE_PAGES;
    EraseInitStruct.PageAddress = FLASH_USER_START_ADDR; //User defined addr
    EraseInitStruct.NbPages     = 1;

    if (HAL_FLASHEx_Erase(&EraseInitStruct, &PAGEError) != HAL_OK)
    {
        HAL_FLASH_Lock();
        return 0;
    }

    /* Program the user Flash area word by word */
    if (HAL_FLASH_Program(FLASH_TYPEPROGRAM_WORD, address, value) != HAL_OK)
    {
        HAL_FLASH_Lock();
        return 0;
    }

    /* Lock the Flash to disable the flash control register access (recommended
     to protect the FLASH memory against possible unwanted operation) *********/
    HAL_FLASH_Lock();

    /* Check if the programmed data is OK */
    result = *(__IO uint32_t *)address;

    if(result != value)
        return 0;

    return result;
}
Nguyen
  • 21
  • 1
  • 3