0

I am looking for a way to increment a variable by one each time a button is pressed. Current approach is the following :

    if (redButton.isPressed())
    {
        a++;
        delay(100);
    }

isPressed() just return true if the pin state is HIGH.

delay(100) is used to compensate the small amount of time the button is being pressed. Otherwise a would be incremented multiple times in a single press. But it's blocking behavior, my program can't do anything else during that delay.

In short I'm looking to add a method in my Button class to detect if the button "has just been released".

1

In your approach a button press will be detected every 100ms when you just keep the button pressed. So you have to set a flag when the button is pressed. When the button is not pressed while your flag is set, that's the event you're looking for. In this way you can detect both a button press and a release respectively. As @JRobert mentioned, there still has to be an amount of time between two calls to such a routine to provide some button debouncing.

bool pressed_flag=false;
bool button_timestamp=millis();
uint16_t button_period=100;

if(millis()-button_timestamp>button_period){
  button_timestamp=millis();
  if(redButton.isPressed() && !pressed_flag){
    // button has just been pressed
    // you can do sth. here
    pressed_flag=true;
  }
  else if(!redButton.isPressed() && pressed_flag){
    // button has just been released
    // you can do sth. here
    pressed_flag=false;
  }
}
  • Also use either a timer library, or hand-code with millis(), to come back and check the button after a time. That interval defends against contact chatter or bounce (multiple inputs for a single press). Using the flag prevents you "detecting" one long button press multiple times. And your code will still not get blocked. – JRobert Aug 9 at 14:13
  • @JRobert theoratically my code is allready non-blocking. But I aggree: it doesn't include any debouncing and my routine should only be called in a specific period. – Sim Son Aug 9 at 14:16
  • Agreed - it doesn't block. I just intended to suggest the addition of chatter removal to your already appropriate solution. (And I got caught accidentally submitting a partially-edited comment! ): – JRobert Aug 9 at 14:18
  • @JRobert you're absolutely right, I added what you suggested! – Sim Son Aug 9 at 14:23

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.