【发布时间】:2018-05-09 11:06:24
【问题描述】:
我正在尝试根据切换按钮的按下来闪烁 LED。如果我第一次按下第一个拨动开关,LED 以 5Hz 闪烁,当我第二次按下拨动按钮时,LED 以 6Hz 闪烁,当我第三次按下时,LED 熄灭。
我尝试使用下面的程序,但它没有按我的意愿工作。
// constants won't change. They're used here to set pin numbers:
const int buttonPin = 7; // the number of the pushbutton pin
const int ledPin = 6; // the number of the LED pin
// variables will change:
int buttonState = 0;
// variable for reading the pushbutton status
void setup() {
// initialize the LED pin as an output:
pinMode(ledPin, OUTPUT);
// initialize the pushbutton pin as an input:
pinMode(buttonPin, INPUT);
Serial.begin(9600);
}
void loop() {
int x=0;
// read the state of the pushbutton value:
buttonState = digitalRead(buttonPin);
Serial.print(x);
// check if the pushbutton is pressed. If it is, the buttonState is HIGH:
if (buttonState == HIGH && x==0) {
// turn LED on:
digitalWrite(ledPin, HIGH);
delay(1000);
digitalWrite(ledPin, LOW);
delay(1000);
Serial.print(x);
} else {
// turn LED off:
x = x+1;
}
if (buttonState == HIGH && x==1) {
// turn LED on:
digitalWrite(ledPin, HIGH);
delay(2000);
digitalWrite(ledPin, LOW);
delay(2000);
Serial.print(x);
} else {
// turn LED off:
digitalWrite(ledPin, LOW);
x = x+1;
}
if (buttonState == HIGH && x==2) {
// turn LED on:
digitalWrite(ledPin, HIGH);
delay(3000);
digitalWrite(ledPin, LOW);
delay(3000);
Serial.print(x);
} else {
// turn LED off:
digitalWrite(ledPin, LOW);
x = x+1;
}
if (buttonState == HIGH && x==3) {
// turn LED off:
digitalWrite(ledPin, LOW);
x = 0;
}
}
当我使用此代码时,它适用于第一种情况,即 LED 以 1000 毫秒延迟闪烁,但如果我切换开关,它再次适用于第一种情况。如何让它执行第二个条件,即以 2000 毫秒的延迟闪烁?
【问题讨论】:
-
你的条件逻辑有点不对劲。您是否尝试对此进行调试并查看正在执行哪些“if”分支以及
x会发生什么? -
50Hz 和 60Hz,你确定这些频率是正确的吗?对led来说有点高。
-
对不起,是 5 和 6,我没有关注那个
-
正确的方法是使用硬件外设定时器,并消除按钮按下和延迟之间的紧密耦合。这只有在用户按住按钮超过 2 秒时才有效,这很糟糕。
-
我可以去抖动一个中断触发器吗?