在keil中可以使用下面的方法將數組定義到指定的位置
uint8_t g_usart_rx_buf[USART_REC_LEN] __attribute__ ((at(0X20001000)));
但是這個方法在IAR中是用不了的,通過網上查找各種資料,發現了兩種可用的方法。我這里測試的單片機是stm32f103c8t6,其他單片機的操作方法是一樣的。
第一種方法
先用記事本打開stm32f103xb_flash.icf 這個文件
里面的代碼如下
/*###ICF### Section handled by ICF editor, don't touch! ****/
/*-Editor annotation file-*/
/* IcfEditorFile="$TOOLKIT_DIR$\config\ide\IcfEditor\cortex_v1_0.xml" */
/*-Specials-*/
define symbol __ICFEDIT_intvec_start__ = 0x08000000;
/*-Memory Regions-*/
define symbol __ICFEDIT_region_ROM_start__ = 0x08000000 ;
define symbol __ICFEDIT_region_ROM_end__ = 0x0801FFFF;
define symbol __ICFEDIT_region_RAM_start__ = 0x20000000;
define symbol __ICFEDIT_region_RAM_end__ = 0x20004FFF;
/*-Sizes-*/
define symbol __ICFEDIT_size_cstack__ = 0x400;
define symbol __ICFEDIT_size_heap__ = 0x200;
/**** End of ICF editor section. ###ICF###*/define memory mem with size = 4G;
define region ROM_region = mem:[from __ICFEDIT_region_ROM_start__ to __ICFEDIT_region_ROM_end__];
define region RAM_region = mem:[from __ICFEDIT_region_RAM_start__ to __ICFEDIT_region_RAM_end__];define block CSTACK with alignment = 8, size = __ICFEDIT_size_cstack__ { };
define block HEAP with alignment = 8, size = __ICFEDIT_size_heap__ { };initialize by copy { readwrite };
do not initialize { section .noinit };place at address mem:__ICFEDIT_intvec_start__ { readonly section .intvec };place in ROM_region { readonly };
place in RAM_region { readwrite,block CSTACK, block HEAP };
在這個文件里面添加下面兩行代碼
define region RAM_D1_region = mem:[from 0x20003000 to 0x20004000];
place in RAM_D1_region {section .RAM_D1};
添加完成之后如下
注意添加的第一行代碼中內存地址的范圍要在RAM地址范圍之內,否則就會出錯。這個地址段的名稱 “RAM_D1_region” 和“RAM_D1”自己可以隨便取。添加完之后保持文件。然后在代碼中按照下面這種方式定義數組:
#pragma location = ".RAM_D1"
uint8_t buf1[10]; /* 接收緩沖, 最大USART_REC_LEN個字節. */
第一行是指定數組定義的位置,第二行是自己定義的數組。
下面運行代碼,在觀察窗口中查看數組。
可以看到數組的起始地址為0x20003000,和剛才設置的一樣。
第二種方法
直接在代碼中設置數組位置
#define DATA_ADDR 0x20002000
__root uint8_t buf2[12] @ (DATA_ADDR);
使用宏定義指定數組位置,當然也可以不用宏定義,直接在數組后面寫地址。使用這種方法的話,就不需要修改 stm32f103xb_flash.icf 這個文件內容了,直接使用默認的內容就行。
直接運行程序,觀察數組地址
可以看到buf2數組的起始地址就從0x20002000 開始了。
這里要注意一個問題,如果使用第2種方法的時候,數組大小必須是4的倍數,否則編譯會報錯。
比如這里將數組大小設置為10
這時候編譯就會報錯。
好了,這兩種方法就分享到這,如果后面發現了其他新的方法再補充。