Search code examples
structstm32stm32f4discoveryflash-memorystm32f4

Read/Write Struct to Flash Memory


I want to write the contents of a struct to flash memory in my C program for STM32F4 Discovery board using HAL libraries. This is my struct:

typedef struct
{
    RTC_TimeTypeDef time;
    RTC_DateTypeDef date;
    float Data;
} DataLogTypeDef;

I have the option to write Byte, Half-Word, Word and Double-Word to each memory address at a time using the stm32f4xx_hal_flash.c library function:

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

My struct contains various data types but I'm not sure how to write the contents using only Byte, Half-Word, Word and Double-Word commands at a time?


Solution

  • What you have is a flash writing function that will write a byte, word, or double word.

    If you want to write your structure to flash the simplest way is to view it as a buffer of bytes or words as long as you read it back the same way on the same platform (and with the same C compiler and compile options). Why the same platform? Because different computer platforms can have a different byte ordering for multi-byte values. Why the same compiler and compiler options? Because a different compiler or different options might pack the data in a struct differently.

    So with that in mind, and keeping in mind there's a lot of details you haven't provided regarding how your flash writer should be called, your code might look like this to copy the structure to flash:

    DataLogTypeDef my_data;
    
    ...
    
    int i;
    uint8_t *data_p = &my_data;
    flash_address = //put first flash address here
    
    for ( i = 0; i < sizeof(DataLogTypeDef); i++, data_p++, flash_address++ )
        HAL_FLASH_Program(type_byte, flash_address, *data_p);
    

    I don't know what the values are for the first two arguments, so I just put type_byte and flash_address. I'm also assuming flash address is an integer form and is a byte address.

    If you want to read the structure back, it might look something like this:

    // Initialize i, data_p, and flash_address first
    
    for ( i = 0; i < sizeof(DataLogTypeDef); i++, data_p++, flash_address++ )
        *data_p = Flash_read(flash_address);