网上看了很多关于这方面的操作,都不是很满意。第一,操作麻烦;第二,不通用,使用平台有限。下面总结了一个更简单通用的方法以供参考。
在MCU的使用过程中,偶尔会遇到将flash中的代码复制到RAM中运行的情况,下面就来说一下具体的方法,以28335的flash初始化为例:
1,编写函数,该函数处于flash中,就是我们即将要复制的代码。
void FlashInitCode(void)
{
EALLOW;
//Enable Flash Pipeline mode to improve performance
//of code executed from Flash.
FlashRegs.FOPT.bit.ENPIPE = 1;
// CAUTION
//Minimum waitstates required for the flash operating
//at a given CPU rate must be characterized by TI.
//Refer to the datasheet for the latest information.
#if CPU_FRQ_150MHZ
//Set the Paged Waitstate for the Flash
FlashRegs.FBANKWAIT.bit.PAGEWAIT = 5;
//Set the Random Waitstate for the Flash
FlashRegs.FBANKWAIT.bit.RANDWAIT = 5;
//Set the Waitstate for the OTP
FlashRegs.FOTPWAIT.bit.OTPWAIT = 8;
#endif
#if CPU_FRQ_100MHZ
//Set the Paged Waitstate for the Flash
FlashRegs.FBANKWAIT.bit.PAGEWAIT = 3;
//Set the Random Waitstate for the Flash
FlashRegs.FBANKWAIT.bit.RANDWAIT = 3;
//Set the Waitstate for the OTP
FlashRegs.FOTPWAIT.bit.OTPWAIT = 5;
#endif
// CAUTION
//ONLY THE DEFAULT VALUE FOR THESE 2 REGISTERS SHOULD BE USED
FlashRegs.FSTDBYWAIT.bit.STDBYWAIT = 0x01FF;
FlashRegs.FACTIVEWAIT.bit.ACTIVEWAIT = 0x01FF;
EDIS;
//Force a pipeline flush to ensure that the write to
//the last register configured occurs before returning.
asm(" RPT #7 || NOP");
}
2,在RAM中分配空间,用于copy代码的RAM中运行,这里直接定义一个数组,数组的大小要大于上面代码的空间,具体数字可查看MAP文件确定,这个空间可以大点,留有一些余量。
static Uint16 InitFlashCodeInRam[INIT_FLASH_CODE_MAX_SIZE];
3,定义函数指针类型,后面会用到
typedef void (*pInitFlashInRam)(void);
4,代码执行操作
(1),定义函数指针,指向上面分配的RAM空间,后面就是通过这个函数指针来调用程序运行的。
(2),将flash中的代码复制到RAM中
(3),通过函数指针的方式运行代码
代码如下:
void InitFlash(void)
{
pInitFlashInRam p=(pInitFlashInRam)InitFlashCodeInRam;
memcpy(InitFlashCodeInRam,FlashInitCode,INIT_FLASH_CODE_MAX_SIZE);
(*p)();
}
5,以上操作方式通用性强,操作简单,支持c语言开发的平台均可使用。