DSPIC33 Storing variable in flash

Thread Starter

samudavid

Joined Jan 4, 2018
29
Hi everyone,

I'm not completely sure about a few things about storing variables in flash. Probably you can help me easily.

I have a DSPIC33EV32GM104 in a board running a program that must store some configuration and that configuration can change a few times (let's say 100).

I'm using the attached code to do so and it works nicely. However, I have a few doubts about if the code will always work OK or if a bug could arise.


1 - I don't specify an address in flash memory space, so it's kind of arbitrary. As long as the var is always allocated in the same address the program will work. I suppose that unless I reprogram the device, the address won't change so it will work OK forever (until the flash reach it last erasing cycle).

2 - To program a multipage system, so I erase a different page every time, I have to declare more variables like "dat".

3 - To control in which page is the current information, I can use a counter variable and read only the page with the higher number in it.

I'm especially concern about point 1. I don't want to store the information somewhere and then try to read it from a different location (that would be disastrous).


Thanks a lot for your help.







Code:
//Var for allocating flash memory space
unsigned int __attribute__((space(prog),aligned(_FLASH_PAGE*2))) dat[_FLASH_PAGE];


int ReadFlashConfiguration(int *UserData)
{
_prog_addressT p;
_init_prog_address(p, dat); /* get address in program space */

_memcpy_p2d16(UserData,p,sizeof(t_UserConfiguration));

//Return Magic Word in first byte
return UserData[0];
}

int WriteFlashConfiguration(int *UserData)
{
_prog_addressT p;
int i;
INTERRUPT_GlobalDisable();
_init_prog_address(p, dat); /* get address in program space */
_erase_flash(p); /* erase a page */

for (i=0;i<sizeof(t_UserConfiguration);i=i+2)
{
_write_flash_word32( p+2*i, UserData[i], UserData[i+1]);
}
INTERRUPT_GlobalEnable();

return 1;
}
 
Top