【发布时间】:2014-03-03 15:00:03
【问题描述】:
我编写了一个检测按钮按下的代码,第一次按下按钮时,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();
}
}
}
【问题讨论】:
-
也许您需要在更改计数器时引入延迟,以消除contact bounce?您可能会在 E-Eng 上获得更多帮助。
-
感谢您的及时回复。但另一个问题是总是检测到第一次按下,所以在这种情况下,调用 gloom() 函数,因此 LED 应该持续发光..但它只是暂时发光。
-
我的意思是,如果开关“弹起”,循环可能会将其记录为另一个“按下”。你不会用肉眼看到弹跳,但它几乎总是存在于任何机械开关中。
-
哦,是的,对,感谢您的宝贵意见.. 我会尝试修复弹跳效果。