debouncing buttons

Hi. What i want to do is to debounce as many pushbuttons as i want with as small piece of code as possible. Here's my try of debouncing 4 pusbuttons at negative edge which does not work. :expressionless:
Debouncing pushbuttons is so frustrating to me... Thanks!

unsigned long debounceMillis;
int lastButton2State;
int lastButton3State;
int lastButton4State;
int lastButton5State;


void check_state(int lastButtonState, int button)
{
  if(lastButtonState != button)
  {
    if(digitalRead(button) == LOW && millis() - debounceMillis >= 25)
    {
      debounceMillis = millis();
      lastButtonState = digitalRead(button);
    }
  }
}

void debounce_each_button()
{
  check_state(lastButton2State, digitalRead(button2));
  check_state(lastButton3State, digitalRead(button3));
  check_state(lastButton4State, digitalRead(button4));  
  check_state(lastButton5State, digitalRead(button5));
}

Before you start to develop a solution for bouncing buttons you should think about whether, or why, the bouncing is actually causing a problem.

If you read a button once with buttonState = digitalRead(buttonPin); there cannot be any bounce.

Bounce can only happen if you read a button at least 2 times. Generally speaking if your code goes off and does something before it reads the button again the next read will be a valid one.

If you are only concerned to detect when a button is pressed then only check for that situation - for example

   if (digitalRead(buttonPin) == LOW) {
      buttonPressed  = true;
   }

and set buttonPressed back to false later in your code when appropriate - don't use the button to reset it.

I have never needed to include explicit debounce code in my projects.

...R

Several problems:

  1. You are passing an integer to a function and expecting the function to be able to modify that integer. Integers are passed to functions "by value" so the function is working on a COPY of the integer, not the integer itself. To allow the function to change the value passed in as an argument you have to declare the function argument as a "reference": "int &lastButtonState".

  2. You also can't use the value read from a digital input as a pin number. The pin number and current state of that pin are two entirely different things.

  3. You might have problems with buttons being pressed close in time since they are all sharing a value for "the last time this button went LOW".