0

该程序旨在计算 button1 按下的次数,然后在 button2 按下时跳出循环。button2 就像一个回车键。

如果我在没有 do while 的情况下单独运行 do while 语句中的内容,它将计算每个按钮的按下。我用它来验证我是否正确构建了我的电路。但是由于某种未知的原因,如果我将相同的代码放入 do while 或只是一段时间,则它不会读取引脚。它将在 do while 内循环,但从不退出到最后的 done 语句。如果我在按下两个按钮中的任何一个时启动 arduino,那么它会记录一个按钮被按下,但是一旦我放手,它就不会再做任何事情了。请告诉我我做错了什么。

我的代码

int ledpin = 11;
int button1pin = 7;
int button2pin = 2;
int button1counter = 0;
int button1state = 0;
int lastButton1state = 0;
int button2state = 0;
int lastButton2state = 0;
int button2counter = 0;

void setup() {                
  // initialize the digital pin as an output.
  pinMode(button1pin, INPUT);
  pinMode(button2pin, INPUT);
  Serial.begin(9600);  
}

void loop() {
  button1state = digitalRead(button1pin);
  button2state = digitalRead(button2pin);
   do  {   
    if (button1state != lastButton1state) {
     if (button1state == HIGH) {
       button1counter++;
       Serial.print("number of button 1 pushes: ");
       Serial.println(button1counter);
       }
       lastButton1state = button1state;
     }
   } while(button2state == LOW);



  Serial.println("done");


}

谢谢我改变了它,当然你的权利。但是,我不太明白为什么你的权利。让我以我的理解评论代码,如果我错了,请纠正我。

void setup() {                

  pinMode(button1pin, INPUT);//tells comp to make button 1 input
  pinMode(button2pin, INPUT);//tells comp to make button 2 input
  Serial.begin(9600);  
}

void loop() {
  button1state = digitalRead(button1pin);//tells comp to begin reading pin?  but for how long?
  button2state = digitalRead(button2pin);
   do  {   
4

1 回答 1

1

您在 while 循环之外读取了您的按钮状态,因此您的 button1state 和 button2state 永远不会更新,这就是您进入无限循环的原因,只需进行一点更改:

void loop() {
    do  {
        button1state = digitalRead(button1pin);
        button2state = digitalRead(button2pin);

        if (button1state != lastButton1state) {
            if (button1state == HIGH) {
               button1counter++;
               Serial.print("number of button 1 pushes: ");
               Serial.println(button1counter);
            }
            lastButton1state = button1state;
        }
   } while(button2state == LOW);

  Serial.println("done");


}
于 2013-10-20T21:31:18.633 回答