cancel
Showing results for 
Search instead for 
Did you mean: 

Load and execute code from SD card

chichkinei
Associate II
Posted on September 06, 2013 at 08:37

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.

2 REPLIES 2
Posted on September 06, 2013 at 13:34

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());
}

Tips, Buy me a coffee, or three.. PayPal Venmo
Up vote any posts that you find helpful, it shows what's working..
frankmeyer9
Associate II
Posted on September 06, 2013 at 13:56

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.