2013-09-05 11:37 PM
I want to store part of my code on an SD card and execute it whenever a certain event occurs. I've already figured out how to interface with an SD card so the problem now it getting the machine code into RAM and telling the MCU to execute it. Lets say I read the machine code from the SD card into a buffer first. How would I then go about telling the MCU to execute from the start address of the buffer? Are there any things I need to consider? Should the code be moved from the buffer to a specific address in RAM? (if so, how do I do that?). I've searched around this forum and wasn't able to find out how to do this. I expect it's as simple as changing the PC to the RAM address required, but I don't know how to do that. Any help is appreciated.
2013-09-06 04:34 AM
You want to have code that doesn't make external references (literals, subroutines), and use pc relative code.
#include <
stdio.h
>
#include <
string.h
>
typedef int (*pFunction)(void);
void RamCode(void)
{
static const uint16_t Code[] = { 0xF04F, 0x007B, 0x4770 }; // payload
uint8_t Buffer[16]; // as big as required
pFunction RunCode;
memcpy(Buffer, Code, sizeof(Code)); // Copy code
RunCode = (pFunction)&Buffer[1]; // +1 for Thumb code
printf(''%d
'',RunCode());
}
2013-09-06 04:56 AM
About 30 years ago, such a trick called 'overlay' was in use, especially under CP/M. Modules were linked to one reserved segment in memory space, and swapped into this fixed segment from mass storage. The reason was the limited address space of the (von Neumann) CPUs at that time, mostly 64k. Position independant code was not supported by the Z80 and it's ilk.
However, I would think twice if it's worth the effort. It consumes precious RAM, introduces delays, and, not least, complexity + bugs. If possible, I would pick a part with more Flash.