2014-10-19 41 views
1

單片機:ATmega328P使用C語言檢測單片機ATmega328P上的按鈕信號

我遇到以下代碼的問題。它用於通過連接到PB0的按鈕來控制LED燈。

有2個狀態:
1. state_0 - 所有的指示燈都熄滅。
2. state_1 - 所有指示燈都點亮。

#include <avr/io.h> 

int main(void) 
{ 
    DDRB = 0x00; //set PINB as a input port for receiving PB0 signal 
    DDRD = 0xFF; //set PORTD as a output port for driving the LEDs 
    unsigned char state_0 = 0x00; //all LED bits are off 
    unsigned char state_1 = 0xFF; //all LED bits are on 

    PORTD = state_0 //initialize the state <----Still work here, Not work after this instruction. 

    while(1) 
    { 
     if(PINB0 == 0 && PORTD == state_0)  //when the button is not pressed and the LEDs are off 
     { 
      PORTD = state_0;     //the LED states remain all off 
     } 
     else if(PINB0 == 0 && PORTD == state_1) //when the button is not pressed and the LEDs are on 
     { 
      PORTD = state_1;     //the LED states remain all on 
     } 
     else if(PINB0 == 1 && PORTD == state_0) //when the button is pressed and the LEDs are off 
     { 
      PORTD = state_1;     //the LED states are turned to all on 
     } 
     else         //when the button is pressed and the LEDs are on 
     { 
      PORTD = state_0;     //the LED states are turned to all off 
     } 
    } 
} 

一些測試後,我發現microcontoller無法檢測從PB0任何信號。當我直接將Vcc連接到PB0或直接將GND連接到PB0時,我會得到相同的結果。當我按下按鈕時,沒有任何改變。

while(1) 
{ 
    if (PINB0 == 0) 
     PORTD = 0x00; 
    else 
     PORTD = 0xFF; 
} 

連接在上面的代碼: enter image description here
不起作用 enter image description here


要測試按鈕,我嘗試以下方法。這是工作,所以botton正常工作。
enter image description here


你知道什麼是錯的?
謝謝你的幫助。

+0

如果連直接電連接+ VDD和地不起作用,那麼這看起來像是一個硬件問題。但是,另一個錯誤是IIRC:從輸出端口讀取沒有任何好處(即,它不會導致端口的實際狀態)。你最好自己跟蹤港口的狀態(在一個單獨的變量中)。 – 2014-10-19 10:12:07

回答

3

問題是,你的程序實際上並沒有檢測到狀態的改變 - 如果while循環運行速度不夠快(也許是)即使短暫推按鈕將同時觸發if(PINB0 == 0 && PORTD == state_0)else一部分。

考慮添加某種檢查狀態 - 就像這樣:

int old_state = 0; 

while(1) { 
    if (old_state != PINB0) { 
     if(PINB0 == 0 && PORTD == state_0)  //when the button is not pressed and the LEDs are off 
     { 
      PORTD = state_0;     //the LED states remain all off 
     } 
     else if(PINB0 == 0 && PORTD == state_1) //when the button is not pressed and the LEDs are on 
     { 
      PORTD = state_1;     //the LED states remain all on 
     } 
     else if(PINB0 == 1 && PORTD == state_0) //when the button is pressed and the LEDs are off 
     { 
      PORTD = state_1;     //the LED states are turned to all on 
     } 
     else         //when the button is pressed and the LEDs are on 
     { 
      PORTD = state_0;     //the LED states are turned to all off 
     } 
     } 
     old_state = PINB0; 
    } 

(抱歉壞縮進,這是相當難以得到,就在這裏)