Arduino reading a Single Button Press

I just need a nudge in a general direction of study. No code to post yet. I need an Arduino to respond to a single button press. My experience is that my finger isn't faster than the loop so a loop counter will decrement 2 or 3 times when a digitalread(x)==LOW is used. What is best practice for ensuring that one button press = one loop of an if/then statement.

Take action when it becomes pressed.

Suggest you stick with looking at 'when a switch changes state' rather than its level.

Review this:

FYI

A flag to record the first detection then ignore subsequent detections until the button is released.

I usually post a link to my tutorial, but you said you wanted a nudge, so I won't.

and mind bouncing

This is what I use for a single button. I have a different version for multiple buttons in a list.

const byte ButtonPin = 2;
const unsigned long DebounceTime = 10;


boolean ButtonWasPressed = false;
unsigned long ButtonStateChangeTime = 0; // Debounce timer


void setup()
{
  pinMode (ButtonPin, INPUT_PULLUP);  // Button between Pin and Ground
}


void loop()
{
  checkButton();
}


void checkButton()
{
  unsigned long currentTime = millis();


  boolean buttonIsPressed = digitalRead(ButtonPin) == LOW;  // Active LOW


  // Check for button state change and do debounce
  if (buttonIsPressed != ButtonWasPressed &&
      currentTime  -  ButtonStateChangeTime > DebounceTime)
  {
    // Button state has changed
    ButtonWasPressed = buttonIsPressed;
    ButtonStateChangeTime = currentTime;


    if (ButtonWasPressed)
    {
      // Button was just pressed
    }
    else
    {
      // Button was just released
    }
  }


  if (ButtonWasPressed)
  {
    // Button is being held down
  }
}

My tutorial on Debouncing Switches in Arduino may be helpful

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