2014-02-09 133 views
0

我用我的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已打开)。 我的方法当时以下代替上述第2行:

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

但是,编译器“期望的表达”。 我的错误是什么?我错了什么?

+0

它应该是一个语法错误,其中行是给出错误? –

+0

'do ... while'是一个陈述,而不是一个表达。它不评估任何东西。因此,你不能在'if'语句中使用它。 – 2014-02-09 14:00:28

回答

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++?
+0

实际上,我并没有在我的实际代码中使用printf()。因此,我忘了#include 但上面的提示工作正常,谢谢! – user3289374

+0

@ user3289374很高兴工作。我在答案中镜像了你的“if ... else”结构,但是你可能会缩短它并移除三元运算符。要迂腐,它可能取决于确切的类型,但您可能想尝试像'#define IN_(port,pin,act)(act ==(PIN(port)>> pin&1))'''。 – jerry