2014-02-09 138 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