【发布时间】:2019-05-20 19:59:41
【问题描述】:
我开始编写代码以在按下按钮时点亮 LED。那行得通。 但后来我尝试调整它,使按钮的作用类似于“开-关”开关,您只需按一次即可在状态之间切换。
LED 可与旧代码(如下)一起使用,因此我认为这不是接线问题。 仅供参考,我跳过了设置功能,它和我让它闪烁的时候一样。
// constants won't change. They're used here to
// set pin numbers:
const int buttonPin = 2; // the number of the pushbutton pin
const int ledPin = 13; // the number of the LED pin
// variables will change:
int buttonState = 0; // variable for reading the pushbutton status
int switcher = 0;
void loop() {
// read the state of the pushbutton value:
buttonState = digitalRead(buttonPin);
// check if the pushbutton is pressed.
// if it is, the buttonState is HIGH:
if (buttonState == HIGH) {
if (switcher = 0) {
switcher = 1;
delay(500);
}
else if (switcher = 1) {
switcher = 0;
delay(500);
}
}
if (switcher == 1) {
digitalWrite(ledPin, HIGH);
}
/*
else {
digitalWrite(ledPin, LOW);
}
*/
}
【问题讨论】:
-
确保在
if条件中使用==运算符,而不是赋值运算符=。在这种语言中,非布尔表达式始终为真。
标签: arduino arduino-uno arduino-c++