问题描述
当我按下按钮时它会关闭 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 按钮 LED 不工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!