实现:用开关控制LED灯亮灭时去除按钮抖动的干扰
代码
int a=0;
int BUTTON = 8;
int LED = 13;
int BUTTON_STATE = 0;
int time1=0;
int time2 = 0;
int b=0;//判断是否为抖动状态
void setup() {
pinMode(LED,OUTPUT);
pinMode(BUTTON,INPUT_PULLUP);
}
void loop() {
BUTTON_STATE = digitalRead(BUTTON);
if(BUTTON_STATE==LOW && (a%2)==0){
time2=millis();//开始计时
if(abs(time1-time2)<=20) b=1;//时间间隔太短判断为抖动
else b=0;
if(b==0) a++; //若为抖动,此次不算
}
if(BUTTON_STATE==HIGH && (a%2)==1){
time1=millis();
if(abs(time1-time2)<=20) b=1;
else b=0;
if(b==0) a++;
}
if((a%2)==0 && (a/2)%2==1) digitalWrite(LED,HIGH);
if((a%2)==0 && (a/2)%2==0) digitalWrite(LED,LOW);
}