Debounce on a Pushbutton (short/long press)

I'd like to share an extension to the Debounce on a Pushbutton tutorial. I added check for short/long press, and use it as a separate function.

What do you guys think?

void readShortLongPress()
{
  const uint8_t BUTTON_PIN = 2;
  const unsigned long DEBOUNCE_DELAY = 50ul;
  const unsigned long LONG_PRESS_LIMIT = 400ul;

  // static variables are used to presere their data between function calls
  static bool pressed = false;
  static bool released = false;
  static unsigned long  pressedMillis = 0ul;

  // pull-up, reversed logic needed
  static uint8_t buttonState = HIGH;
  static uint8_t lastButtonState = HIGH;
  static unsigned long lastDebounceTime = 0ul;

  // gather current state
  int reading = digitalRead(BUTTON_PIN);
  unsigned long currentMillis = millis();

  if (reading != lastButtonState)
  {
    lastDebounceTime = currentMillis;
  }

  if ((currentMillis - lastDebounceTime) > DEBOUNCE_DELAY )
  {
    if (reading != buttonState)
    {
      buttonState = reading;

      if (buttonState == LOW)
      {
        pressed = true;
        pressedMillis = currentMillis;
      }
      else
      {
        released = true;
      }
    }
  }

  // button was pressed, but not anymore
  if (pressed && released)
  {
    // compare current millis with the timestamp of the last press
    if ((currentMillis - pressedMillis) >= LONG_PRESS_LIMIT )
    {
      longButtonPress = true;
    }
    else
    {
      shortButtonPress = true;
    }

    // flip them back
    pressed = false;
    released = false;
  }

  lastButtonState = reading;
}

why not use a library? Bounce2 is good

That method makes the output lag the press by DEBOUNCE_DELAY, which isn't necessary (or sometimes desirable).

Schemes like this are more responsive:

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