Arduino button LED not working

只谈情不闲聊 提交于 2019-12-11 05:35:46

问题


When I push the button it turns the KY008 off but when I click it again it won't turn it off, but if I jiggle the Laser Diode a little bit the KY008 turns back on.

Code:

int LED = 12;
int BUTTON = 4;

void setup(){
   pinMode(LED,OUTPUT);
   pinMode(BUTTON,INPUT);
}

void loop(){
    if(digitalRead(BUTTON) == HIGH){
        digitalWrite(LED,HIGH);
    }else{ 
    digitalWrite(LED,LOW);
    }
}

回答1:


If you use INPUT you need to have a physical pullup (or pulldown) resistor (typically 10k).

Otherwise use INPUT_PULLUP to use the Arduino internal pullup resistors

pinMode(BUTTON, INPUT_PULLUP);

Make sure that your button closes the circuit to ground when pressed.

Also when reading a button you will have a lot of bouncing. The easiest way to prevent the bouncing is to add a delay between reads.

void loop(){
    if(digitalRead(BUTTON) == HIGH){
        digitalWrite(LED,HIGH);
    }else{ 
        digitalWrite(LED,LOW);
    }
    delay(100);
}


来源:https://stackoverflow.com/questions/48646503/arduino-button-led-not-working

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!