使用C语言检测微控制器ATmega328P上的按钮信号

时间:2014-10-19 10:04:52

标签: c microcontroller led

微控制器:ATmega328P

我遇到以下代码的问题。它用于通过连接到PB0的按钮控制LED灯。

有2个州:
 1. state_0 - 所有LED均熄灭  2. state_1 - 所有LED均亮起。

#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
        }
    }
}

经过一些测试,我发现微控制器无法检测到来自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


你知道出了什么问题吗? 谢谢你的帮助。

1 个答案:

答案 0 :(得分:3)

问题是你的程序实际上没有检测到状态的变化 - 如果while循环运行得足够快(可能是),即使简短按下按钮也会触发if(PINB0 == 0 && PORTD == state_0)和{{1部分。

考虑添加某种检查状态 - 如下所示:

else

(对于糟糕的缩进感到抱歉,很难在这里得到它)