#定义与枚举解决外设 [英] #define vs. enums for addressing peripherals
问题描述
我要在基于ARM9微控制器外设寄存器进行编程。
I have to program peripheral registers in an ARM9-based microcontroller.
例如,对于USART,我相关的存储器地址存储在一个枚举
:
For instance, for the USART, I store the relevant memory addresses in an enum
:
enum USART
{
US_BASE = (int) 0xFFFC4000,
US_BRGR = US_BASE + 0x16,
//...
};
然后,我用指针的函数来初始化寄存器:
Then, I use pointers in a function to initialize the registers:
void init_usart (void)
{
vuint* pBRGR = (vuint*) US_BRGR;
*pBRGR = 0x030C;
//...
}
但我的老师说我最好使用的#define
S,如:
#define US_BASE (0xFFFC4000)
#define US_BRGR (US_BASE + 0x16)
#define pBRGR ((vuint*) US_BRGR)
void init_usart (void)
{
*pBRGR = 0x030C;
}
就像这样,他说,你没有在堆栈中分配指针的开销。
Like so, he says, you don't have the overhead of allocating pointers in the stack.
就个人而言,我不喜欢的#define
取值多少,也没有其他的preprocessor指令。
所以,问题是,在这种特殊情况下,为的#define
真是值得使用的,而不是枚举
和stack-分配的指针?
Personally, I don't like #define
s much, nor other preprocessor directives.
So the question is, in this particular case, are #define
s really worth using instead of enum
s and stack-allocated pointers?
推荐答案
我有这种方法总是preferred是先定义一个结构反映了外设寄存器布局
The approach I've always preferred is to first define a struct reflecting the peripherals register layout
typedef volatile unsigned int reg32; // or other appropriate 32-bit integer type
typedef struct USART
{
reg32 pad1;
reg32 pad2;
reg32 pad3;
reg32 pad4;
reg32 brgr;
// any other registers
} USART;
USART *p_usart0 = (USART * const) 0xFFFC4000;
然后在code,我可以只使用
Then in code I can just use
p_usart0->brgr = 0x030C;
这方法是干净多了,当你有相同的排序周边的多个实例:
This approach is much cleaner when you have multiple instances of the same sort of peripheral:
USART *p_usart1 = (USART * const) 0xFFFC5000;
USART *p_usart2 = (USART * const) 0xFFFC6000;
用户sbass提供的链接<一个href=\"http://www.embedded.com/design/programming-languages-and-tools/4027659/Alternative-Models-for-Memory-Mapped-Devices\"相对=nofollow>由Dan Saks的一个很好的列,让这种技术更多的细节,并在其他方法指出了它的优势。
User sbass provided a link to an excellent column by Dan Saks that gives much more detail on this technique, and points out its advantages over other approaches.
如果你有幸使用C ++,那么你可以添加方法对周围所有的常用操作,并很好地封装设备的特殊性。为
If you're lucky enough to be using C++, then you can add methods for all the common operations on the peripheral and nicely encapsulate the devices peculiarities.
这篇关于#定义与枚举解决外设的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!