Only return button state once in X amount of time?

I want to detect if a button has been pressed, but what I don't want is for it to keep returning the "pressed" state more than once within a second or two.

For example, with this code:

void loop() {
  passButtonState = digitalRead(passButton);

  if (passButtonState == LOW) {
    Serial.println("PASSED!");
  }
}

Would spit out something like this with a single quick press of the button: link

PASSED!
PASSED!
PASSED!
PASSED!
PASSED!
PASSED!
PASSED!
PASSED!
PASSED!

But what I want is for a single button press to just return PASSED! once for that single button press.

Welcome to the forum
Ie you want standard button press code that is used in most examples. Detect not that the button is pressed but when the button becomes pressed (edge detection). With debouncing this should happen only once for each button press.

The Arduino state change detection is a good tutorial, but it uses an active high switch. The more popular way to wire a switch is to wire it to ground and an input with the internal pullup enabled (active low). Here is my state change detection for active low switches.

Or look up easybutton library

But in that case one does not learn much :wink:

True, except in my case how to use a library, but it solved my problem.

detecting a "state change" is applicable to other inputs beside buttons

consider

// simple button processing

const byte butPin = A1;
byte       ledPin = 13;

byte butState;

enum { Off = HIGH, On = LOW };

// -----------------------------------------------------------------------------
void loop (void)
{
    byte but = digitalRead (butPin);

    if (butState != but)  {     // check that button state changed
        butState = but;
        delay (10);         // debounce

        if (LOW == but)     // button pressed
            digitalWrite (ledPin, ! digitalRead (ledPin));
    }
}

// -----------------------------------------------------------------------------
void setup (void)
{
    digitalWrite (ledPin, Off);
    pinMode      (ledPin, OUTPUT);

    pinMode     (butPin, INPUT_PULLUP);
    butState  = digitalRead (butPin);
}

That's cool, I can use that to solve a current problem! Thanks.

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.