首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在arduino上使用变量按钮停止while循环

在arduino上使用变量按钮停止while循环
EN

Stack Overflow用户
提问于 2020-01-25 21:06:00
回答 1查看 520关注 0票数 0

对于Arduino,我从电位器获取模拟输入。通过输入,我可以调节我的灯闪烁的程度。问题是当我试图让一个按钮来打开和关闭灯,使它闪烁或不闪烁。我可以让按钮打开灯,但我不能让它关灯。

我的让灯闪烁的循环有一个变量,它必须为1才能运行。但是,当我使用if语句将变量更改为0时,闪烁循环不会停止,并且灯继续闪烁。

下面是我的代码:

代码语言:javascript
复制
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);
  }

}

感谢您的帮助!

EN

回答 1

Stack Overflow用户

发布于 2020-01-25 21:37:04

while inside循环总是可疑的,您提供了一个很好的例子。

在while循环中,buttonState永远不会改变,因此您永远有一段时间

只需将其更改为if,您的草图就会表现得更好。

表明delay(1000);不是按钮处理的最佳选择。您更希望处理状态更改(并考虑跳动按钮)。但这是一个高级问题。:)

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/59909514

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档