How does MCU implement part of the code running in RAM?
[Copy link]
MCU is different from the resource-rich Linux platform. MCU (such as Cortex M0+ based on Cortex V6M, etc.) Code usually runs in embedded Flash. In some specific applications, some functions need to run in RAM. Yesterday, in order to solve this problem, a solution was implemented. The specific steps are as follows:
1. Implement the routine to be run in RAM. This routine is implemented in pure assembly, such as:
__asm void program_word2addr(uint32_t addr, uint32_t data)
{
push {r3, r4, r5, lr} ;save some regsiters
/*your code for this routine*/
pop {r3, r4, r5, pc}
}
2. When compiling, use the compile option that code is independent of the running position, such as (Keil --apcs /ropi/rwpi), to generate *.axf;
3. Use fromelf -c to disassemble the generated *.axf, find the corresponding program_word2addr implementation part, and copy the binary code corresponding to the routine to the code to be applied, which will appear in the form of a read-only array:
like:
const staic uint16_t s_flashProg2AddressCode[16] = {...., ....}
4. Define a global array, such as static uint16_t g_code[16], whose size is exactly equal to the length of s_flashProg2AddressCode;
5. Define a function pointer, such as static void (*callFlashPrg2Address)(uint32_t addr, uint32_t data)
6. Define a function to run the code in RAM as follows:
void run_prgcode_onram(uint32_t addr, uint32_t data)
{
memcpy(g_code,s_flashProg2AddressCode,32);
callFlashPrg2Address = (void (*)(uint32_t addr, uint32_t data))((uin32_t)g_code + 1);
callFlashPrg2Address (address, data);
}
run_prgcode_onram, then program_word2addr can be run in RAM.
callFlashPrg2Address = (void (*)(uint32_t addr, uint32_t data))((uin32_t)g_code + 1); The purpose of +1 is that the operating platform is Cortex V6M, using the thumb instruction set, which is completed according to the ARM Spec requirements.
callFlashPrg2Address (address, data); is the key to realize RAM running program_word2addr.
|