对于Arduino,我从电位器获取模拟输入。通过输入,我可以调节我的灯闪烁的程度。问题是当我试图让一个按钮来打开和关闭灯,使它闪烁或不闪烁。我可以让按钮打开灯,但我不能让它关灯。
我的让灯闪烁的循环有一个变量,它必须为1才能运行。但是,当我使用if语句将变量更改为0时,闪烁循环不会停止,并且灯继续闪烁。
下面是我的代码:
int sensorPin = A0; // select the input pin for the potentiometer
int ledPin = 13; // select the pin for the LED
int sensorValue = 0; // variable to store the value coming from the sensor
int buttonPin = 11; //select the pin for the button
int buttonState = 0; //variable to start and stop the led
void setup() {
pinMode(ledPin, OUTPUT);
pinMode(buttonPin, INPUT);
}
void loop() {
if(digitalRead(buttonPin)==HIGH){
buttonState = 1;
delay(1000) //So that buttonState does not instantly change back
}
if(digitalRead(buttonPin)==HIGH && buttonState == 1;){
buttonState = 0;
delay(1000) //So that buttonState does not instantly change back
}
while(buttonState == 1){
// read the value from the sensor:
sensorValue = analogRead(sensorPin);
// turn the ledPin on
digitalWrite(ledPin, HIGH);
// stop the program for <sensorValue> milliseconds:
delay(sensorValue);
// turn the ledPin off:
digitalWrite(ledPin, LOW);
// stop the program for for <sensorValue> milliseconds:
delay(sensorValue);
}
}感谢您的帮助!
发布于 2020-01-25 21:37:04
while inside循环总是可疑的,您提供了一个很好的例子。
在while循环中,buttonState永远不会改变,因此您永远有一段时间
只需将其更改为if,您的草图就会表现得更好。
表明delay(1000);不是按钮处理的最佳选择。您更希望处理状态更改(并考虑跳动按钮)。但这是一个高级问题。:)
https://stackoverflow.com/questions/59909514
复制相似问题