2016-10-08 36 views
0

如何使用開關結構增加狀態。我需要一個計數++嗎?我在交換機(expr)中放置了[(((button_in & 0x0040)!= 0)]表達式。這給了我前兩個我想要的狀態。 (1)按按鈕1產生0001.(2)按鈕2產生0010. 我不確定如何編程按鈕1 TWICE爲了產生0010.我在while循環中實現了一個計數嗎?我可以使用while表達式作爲計數嗎?我應該在級聯中放置另一個while循環嗎?我想增加我的狀態。有7個州:0000,0001(5美分),0010(10美分),0011(15美分),0100(20美分),1000(25美分),0111(更改)。 我更新了我的問題和代碼,試圖清楚地反映我的意圖。 我不是程序員,我的朋友提到,當我按下按鈕;我應該檢查當前狀態;然後編程我的代碼。他還提到了一個二進制計算器。哪種方法最有效?由於C開關計數增加狀態

int main() 
{ 
    char A; //placed for switch expression... (not needed?) 
    int button_in = 0; // button is set for 0 (not-engaged) 
    DeviceInit(); //set LED1 thru LED4 as digital output 
    DelayInit(); //Initialize timer for delay 
    int count; //maybe required for 5 button pushes. Requesting help with this 

    while (1) //Can I initiate a count? for a second button push? 
    { 
    button_in = PORTReadBits(IOPORT_A, BIT_6 | BIT_7); //Button 1 and button 2 defined 
    if (button_in != 0) //if button is engaged utilize switch statement 
    { 
     switch ((button_in & 0x0040) != 0) //if button1 is engaged 
     { 
     case 0: 
     ((button_in & 0x0080) != 0); //Statement: Button2 engages case0 
     PORTWrite(IOPORT_B, BIT_11); //State goes to 010 (BIT_11 lights up). 
     break; 

     default: ((button_in & 0x0040) != 0); //Statement: Button1 engages default. 
     PORTWrite(IOPORT_B, BIT_10); //This is state 0001 (BIT_10) lights up. 
     break; 
     } 

     DelayMs(100); //100millisecond delay for light shine 
     PORTClearBits(IOPORT_B, BIT_10 | BIT_11 | BIT_12 | BIT_13); //ClearLEDs 
    } 
    } 
} 
+0

我想你需要的是一個狀態機 – Mobius

回答

0

首先,在我看來,做switch ((button_in & 0x0040) != 0)應該避免,因爲你可以通過一個簡單的if聲明,這將是更常見,更易於閱讀取代它。

然後,當談到自己的狀態問題,在這種特定情況下的狀態機

(o)-->(s1)-->(s2)-->(s3)-->(s4)-->(s5)-->(s6)-->((s7)) 

在這一個過渡看起來每次按下button 1時發生,你可以簡單地增加一個計數器指示你當前處於哪個狀態(如果你想從終端回到初始狀態,則以模8爲模)。在IOPORT_B[1]波紋管)上寫入的正確值可以在檢查計數器的二進制值之後確定,也可以在進入循環之前將其存儲在數組中,並使用arr[state]進行檢索。選擇取決於你的應用和價值。

int main() 
{ 
    int state = 0; 
    while(1) 
    { 
     if (button 1 is pressed) 
     { 
     state = (state >= 7) ? 7 : (state + 1); 
     PORTWrite(IOPORT_B, ...);  // [1] 
     DelayMs(100);     // wait 
     PORTClearBits(IOPORT_B, ...); // Clear what you want to clear 
     } 
    } 
} 
+0

我試圖實現的,如果從一開始就聲明,但沒有爲我工作了太順利。 – Jeremiah

+0

沒有進一步的信息,我不能幫助更多。這取決於你的'PORTReadBits'返回什麼。但絕對是,你在代碼中做了奇怪的事情。就像'case 0:'和'default'後面的語句只是比較,因爲你沒有使用它們的結果是沒有意義的。也許你不太瞭解'switch'語句。 –

+0

想通了。感謝您的輸入。 – Jeremiah