Arduino button debounce function

Arduino button debounce function

Physical buttons and switches do not switch between open and close position instantly and perfectly. Instead, they have a tendency to "bounce" between the two states before settling on one. This issue is thoroughly described in circuitdigest's excellent article. Consequently, when using such components with, for example, an Arduino microcontroller, a proper debouncing algorithm must be implemented.

Here is a code sample for my approach to solving the problem.

int readButtonDebounce(int pin) {
  const int DEBOUNCE_DELAY = 50;
  static int buttonState, lastButtonState;
  static long lastDebounceTime; 
  int out = 0;

  int reading = digitalRead(pin);
  if(reading != lastButtonState) lastDebounceTime = millis();

  if((millis() - lastDebounceTime) > DEBOUNCE_DELAY) {
    if (reading != buttonState) {
      buttonState = reading;
      // CHANGE TO !buttonState if active low
      if(buttonState) {
        out = 1;
      }
    }
  }
  lastButtonState = reading;
  return out;
}