在AVR中未检测到按钮按下

时间:2014-03-03 15:00:03

标签: avr gpio

我已经编写了一个代码,可以检测到按下按钮,第一次按下按钮时LED会发光,下次按下时,LED应该关闭,如果按下第三次,LED应该按下再次发光。

问题是,控制器能够检测按钮按下但不是长时间打开LED,它只是暂时将其打开然后再次关闭。并且未检测到进一步按下按钮。

以下是代码:

#include <avr/io.h>
#include <avr/delay.h>

void glow();
void off();
void switchScan();

int main()
{
DDRA=0x02; // 0000 0010 --> BIT 0=connected to switch whose other pin is connected to   ground,, and BIT 1 is connected to LED with other pin of led connected to ground
PORTA=0x01; // 0000 0001---> Switch Input pulled up and LED output pulled down 

while(1)
{
switchScan();
}

return 0;
}


void glow()
{
PORTA=PORTA|(1<<1);
}

void off()
{
PORTA=PORTA&(~(1<<1));
}

void switchScan()
{
 static int counter=0;
if(~(PINA & 0x01))
{ 
 counter++;
if(counter < 2)
glow();
else
{
counter--;
off();
}
}
}

1 个答案:

答案 0 :(得分:2)

switchScan()函数中的逻辑存在缺陷。 glow()只会执行一次。参见代码注释:

void switchScan() {
    static int counter=0;

    if (~(PINA & 0x01)) { 
        counter++;
        // 1st button press: counter will be 1
        // 2nd and all following button presses: counter will be 2
        if (counter < 2)
            // can only be called once!
            glow();
        else {
            // counter will always go from 2 to 1 at this point 
            counter--;
            off();
        }
    }
}

但是,你也应该考虑Brett在评论中提到的反弹。

相关问题