Content originally posted in LPCWare by MarcVonWindscooting on Fri Mar 14 08:31:13 MST 2014
Difficult question.
First of all, FLASH write access must be done with the size and alignment of a page.
If by 'variable' you mean an initialized (by the startup code) variable - a variable deposited in the section .data - then there's no need to read the FLASH, as the startup code has already done for you before handing over control to your main() .
The initialization values of the .data section are stored in FLASH. You have to look into your linker script and find the start of the initialization data of the .data section. Let's assume, you find it named '__data_image'. You'll recognize it by a statement
__data_image = . ;
in the linker script.
Then you can pretend in C code...
extern char __data_image;
...that a char is located at __data_image. &__data_image is then the address of the .data section's initialization image.
You can do the same with the start of .data, something like __data_start will be defined somewhere in the linker script.
extern char __data_start;
If your variable is named 'var', then offset = (char*)&var - &__data_start is the (byte) offset of var inside .data what is the same as the offset of the initialization value for var in the initialization image. Hence, var's FLASH address is &__data_image + offset . This is the address you're interested in.
Depending on your compilation environment, the values for &__data_start and &__data_image (or similar names) are handed to you on a silver platter ;-)
But to be honest, I would not do it that way. It's much easier to put all your state + a magic number in a structure called state and read that structure from FLASH at program startup (inside main()) and write that state structure to FLASH on demand. As address, choose a FLASH sector/page your program doesn't use so far. That way, you don't need to know such details as described above.
EDIT: added missing '&'