问题描述
当我按下按钮时,它将关闭KY008,但是当我再次单击它时,它不会将其关闭.但是,如果我稍微摇动激光二极管,则KY008会重新打开.
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.
代码:
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);
}
}
推荐答案
如果使用INPUT
,则需要一个物理上拉(或下拉)电阻(通常为10k).
If you use INPUT
you need to have a physical pullup (or pulldown) resistor (typically 10k).
否则,请使用INPUT_PULLUP
使用Arduino内部上拉电阻器
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);
}
这篇关于Arduino按钮指示灯不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!