简体   繁体   English

Arduino IDE-按下按钮时停止重复“ Serial.println”

[英]Arduino IDE - Stopping repeat 'Serial.println' when button pressed

I'm working on a project where, when you press a button and it displays a value in the Serial Monitor (not the most exciting granted but this is my first none-tutorial project), the code for this is: 我正在一个项目中,当您按一个按钮时,它在串行监视器中显示一个值(不是最令人激动的授予,但这是我的第一个非教程项目),此代码为:

void loop() {

   if(digitalRead(firstButton) == HIGH) {    
      digitalWrite(firstLed, HIGH);    
      Serial.println("First button pressed");
      delay(250);
   }

   if(digitalRead(secondButton) == HIGH) {    
      digitalWrite(secondLed, HIGH);    
      Serial.println("Second button pressed");
      delay(250);
   }

}

This largely does what you would expect it to, however if you hold the button down it repeats the 'Serial.println' value continuously until the button is released. 这在很大程度上满足了您的期望,但是,如果按住该按钮,它将连续不断地重复'Serial.println'值,直到释放按钮为止。 Ideally I need this to state the 'Serial.println' value once per press, regardless of whether it is held down for a second or a minute. 理想情况下,无论每次按下一秒钟还是一分钟,我都需要使用此状态来每次按一次来声明“ Serial.println”值。

Any help would be greatly appreciated... 任何帮助将不胜感激...

No idea if it matters but I'm using an Arduino Uno R3 with a Wi-Fi shield (which is giving me all kinds of grief but thats for another day). 不知道这是否重要,但我使用的是带Wi-Fi防护罩的Arduino Uno R3(这给我带来了各种各样的悲伤,但又过了一天)。

In order to detect a keypress change, you need to detect the button state change event. 为了检测按键更改,您需要检测按钮状态更改事件。 In which case you need to keep track of the previous button state: 在这种情况下,您需要跟踪先前的按钮状态:

void loop() {

    static int firstPrevious = LOW;
    static int secondPrevious = LOW;

    int first = digitalRead(firstButton);
    int second = digitalRead(secondButton);

    if((first == HIGH) && (firstPrevious == LOW)) {
        digitalWrite(firstLed, HIGH);
        Serial.println("First button pressed");
        delay(250);
    }

    if((second == HIGH) && (secondPrevious == LOW)) {
        digitalWrite(secondLed, HIGH);
        Serial.println("Second button pressed");
        delay(250);
    }

    firstPrevious = first;
    secondPrevious = second;
}

After this, you'll want to look into switch "de-bounce" so you don't get multiple events for each keypress... 在此之后,您将需要查看“去反弹”开关,以免每次按键都遇到多个事件...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM