宏功能读取寄存器

时间:2014-02-09 13:44:59

标签: c macros

我使用MSP430的以下宏功能来检查GPIO引脚的状态:

#define PIN(port)             port##IN                    // register name

#define IN_(port,pin,act)     PIN(port) & (1<<(pin))      // request pin status

#define IN(name)              IN_(name)                   // final macro function call

然后我能够获得GPIO引脚的状态,如:

enum {ACT_LOW = 0 , ACT_HIGH};
#define STATUS_LED      P3,0,ACT_LOW         // P3       ... port name, 
                                             // 0        ... associated port pin,
                                             // ACT_LOW  ... pin intended for active low action

void main()
{
  if(!IN(STATUS_LED))
     printf("Status LED connected to P3.0 is switched on");
  else
     printf("Status LED connected to P3.0 is switched off");
}

现在我想把我的引脚的活动状态考虑在内,以免在编程时我的LED切换到低端('0'= LED打开)。 我的方法是以下而不是前面提到的第二行:

#define IN_(port,pin,act)           \
 do{                                \
    if((act) == ACT_HIGH)           \
     PIN(port) & (1<<(pin));        \
    else                            \
     ~(PIN(port) & (1<<(pin)));     \
   }while(0) 

但是,编译器'需要一个表达式'。 我的错是什么?我有什么问题?

1 个答案:

答案 0 :(得分:0)

以下代码

#define PIN(port)             port##IN                    // register name
#define IN_(port,pin,act)           \
 do{                                \
    if((act) == ACT_HIGH)           \
     PIN(port) & (1<<(pin));        \
    else                            \
     ~(PIN(port) & (1<<(pin)));     \
   }while(0)
#define IN(name)              IN_(name)                   // final macro function call

enum {ACT_LOW = 0 , ACT_HIGH};
#define STATUS_LED      P3,0,ACT_LOW         // P3       ... port name, 
                                             // 0        ... associated port pin,
                                             // ACT_LOW  ... pin intended for active low action

void main()
{
  if(!IN(STATUS_LED))
     printf("Status LED connected to P3.0 is switched on");
  else
     printf("Status LED connected to P3.0 is switched off");
}

do...while语句扩展为if语句的控制表达式。你不能这样做。另一种方法是使用三元运算符:

#define IN_(port,pin,act) ((act) == ACT_HIGH ? PIN(port) & (1<<(pin)) : ~(PIN(port) & (1<<(pin))) )

还要注意以下问题:

  1. 您没有#include <stdio.h>
  2. ~(PIN(port) & (1<<(pin)))应为!(PIN(port) & (1<<(pin)))(~PIN(port))&(1<<(pin))
  3. 为了便于携带,main应返回int(请参阅What should main() return in C and C++?