按键消抖——消抖中的消抖_From UU
本帖最后由 touchfree 于 2015-4-2 22:08 编辑基于“传统消抖不稳定,delay延时带来的不便”的更新算法:
byte LED = 13;
byte BUTTON = 3;
void setup(void)
{
pinMode(LED,OUTPUT);
pinMode(BUTTON,INPUT_PULLUP);
digitalWrite(LED,LOW);
}
void loop(void)
{
static unsigned long timepoint = millis();
static byte count = 0;
if(millis()-timepoint > 10)
{
timepoint = millis();
if(digitalRead(BUTTON)) count = 0;
if( (count<100) && (++count==10) )
digitalWrite(LED, digitalRead(LED)^1);
}
}
下来我们来理解下上边的程序:
byte LED = 13;
byte BUTTON = 3;
void setup(void)
{
pinMode(LED,OUTPUT);
pinMode(BUTTON,INPUT_PULLUP);
digitalWrite(LED,LOW);
}
void loop(void)
{
static unsigned long timepoint = millis();
static byte count = 0;
if(millis()-timepoint > 10)
{
timepoint = millis();
if(digitalRead(BUTTON)) count = 0;
else if( (count<100) && (++count==5) )
digitalWrite(LED, digitalRead(LED)^1);
}
}
或者 这个一样的:byte LED = 13;
byte BUTTON = 3;
void setup(void)
{
pinMode(LED,OUTPUT);
pinMode(BUTTON,INPUT_PULLUP);
digitalWrite(LED,LOW);
}
void loop(void)
{
static unsigned long timepoint = millis();
static byte count = 0;
if(millis()-timepoint > 10U)
{
timepoint = millis();
switch(digitalRead(BUTTON))
{
case 1:
count = 0;
break;
case 0:
{
if( (count<100) && (++count==5) )
digitalWrite(LED,digitalRead(LED)^1);
}
break;
}
}
}
Note: 源于悠悠大神的智慧算法,转载需注明出处!
tutorials
页:
[1]