我为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)
但是,编译器“期望表达式”。
我怎么了我怎么了?
最佳答案
以下代码
#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))) )
另请注意以下问题:
您没有
#include <stdio.h>
~(PIN(port) & (1<<(pin)))
应该是!(PIN(port) & (1<<(pin)))
或(~PIN(port))&(1<<(pin))
为了便于移植,
main
应该返回一个int
(请参阅What should main() return in C and C++?)关于c - 宏功能读取寄存器,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/21659786/