问题
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