(This question is specific for the Arduino Due, but maybe there's a general answer to the question)
I'm using DueFlashStorage to store application data in the flash memory of my Arduino Due. That works quite nicely. The Due has two flash blocks with 256k each. By default, the library writes data to the second flash block. The first flash block is used for the program. My program currently uses around 160k of flash (as the compiler tells me). That leaves about 96k of flash unused, which I could really use to store more application data. I managed to adjust DueFlashStorage to allow writing to the full memory range, but how do I detect where it is safe to write to? (Obviously, I must not overwrite any part of the program)
I have tried something like:
// this returns the logical address of the first byte in flash (0x80000)
byte* startAddr = dueFlashStorage.readAddress(0);
Serial.println((unsigned int)startAddr, HEX);
int bytes = 0;
while (bytes < 512 * 1024) // That's the size of the flash
{
int* data = (int*)(startAddr + bytes);
if (*data == 0xFFFFFFFF) // empty flash is initialized with FF's
{
Serial.print("Free block at 0x");
Serial.println((unsigned int)data, HEX);
}
else
{
Serial.print("Used block at 0x");
Serial.println((unsigned int)data, HEX);
}
bytes+=512;
}
This seems to work, as the first block detected as "free" is just above the size of the program. However, this approach has some major drawbacks:
- It's slow. Running over the whole address space to find the end of the program uses time (and maybe I shouldn't just test the first word of each block)
- It's not reproducible. After I have written data to the detected first free block, it's no longer free, so I need another approach (like some magic number) to detect the first data block after the CPU is reset.
Is there a better way for this (like, in the ideal world, a constant I could use)? I don't want to hardcode the data start, because as the program grows (and it's still in development) I would forget to adjust that constant and booooommmm....