define与枚举寻址外设

define与枚举寻址外设

本文介绍了#define与枚举寻址外设的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须在基于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,例如:

But my teacher says I'd better use #defines, such as:

#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 ,也不是其他预处理指令。
所以问题是,在这种特殊情况下, #define 真的值得使用,而不是枚举 s和堆栈分配的指针?

Personally, I don't like #defines much, nor other preprocessor directives.So the question is, in this particular case, are #defines really worth using instead of enums and stack-allocated pointers?

相关问题:

推荐答案

我一直喜欢的方法是首先定义反映外设寄存器布局的结构

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;

然后在代码中我可以使用

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提供了一个链接到,以及指出其优于其他方法的优势。

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.

这篇关于#define与枚举寻址外设的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-04 14:32