Saving user parameters in flash

I created read/write functions

typedef struct
{
////////////////////////////
}SYS_PARAMS;

SYS_PARAMS sys_parameters;


void SYS_ParamRead()
{   
    FlashMemory.read();
    memcpy(&sys_parameters, &FlashMemory.buf, sizeof(SYS_PARAMS));
}

void SYS_ParamWrite()
{
    memcpy(&FlashMemory.buf, &sys_parameters, sizeof(SYS_PARAMS));
    FlashMemory.update();
}

When I invoke SYS_ParamWrite() I’m stuck in the function. Probably some hardware exception due to memory access.
What is wrong with my method?

Ooops…Just my typo

         //not &FlashMemory.buf
memcpy(&sys_parameters, FlashMemory.buf, sizeof(SYS_PARAMS));
memcpy(FlashMemory.buf, &sys_parameters, sizeof(SYS_PARAMS));

And I set an option - erase the page before write

FlashMemory.update(1);

Now it’s OK but after a restart - no parameters are saved.

1 Like

Hi @john7 Thanks for providing the detailes,

May I know what you put for the base address? and approx how big is your data being stored?

I don’t do it explicitly
//FlashMemory.begin(0x00100000, 0x1000);
because it’s initialized in the class

FlashMemoryClass FlashMemory = FlashMemoryClass(FLASH_MEMORY_APP_BASE, FLASH_SECTOR_SIZE);

Structure size about 512 bytes.
I thought because my struct is not packed it’s not aligned properly, so I did a test

void SYS_ParamWrite()
{
    //memcpy(FlashMemory.buf, &sys_parameters, sizeof(SYS_PARAMS));
    FlashMemory.buf[0] = sys_parameters.debug; //uint8_t
    FlashMemory.update(1);
}

void SYS_ParamRead()
{   
    FlashMemory.read();
    //memcpy(&sys_parameters, FlashMemory.buf, sizeof(SYS_PARAMS));
    sys_parameters.debug = FlashMemory.buf[0];
}

The parameter is not saved.

Ohhh…Sorry. It seems like the problem because my struct is not packed.

1 Like