MajicDesigns / MD_UISwitch

Uniformly encapsulate different types of switches as user input devices
GNU Lesser General Public License v2.1
40 stars 17 forks source link

Debouncing Algorithm sensitive to short presses #3

Closed fleetingbytes closed 6 years ago

fleetingbytes commented 6 years ago

Hello Marco,

I see an issue with the debouncing algorithm. It doesn't ignore presses shorter than the debounce time. When I press a single digital button shorter than the duration set in setDebounceTime(), the keyResult_t still returns a KEY_SINGLE event.

Isn't the whole idea of debouncing such that only after the button has been continuously and steadily pressed for the time defined in setDebounceTime(), only then it is supposed to send the logical signal of a keypress?

I tested this with a purposefully long debounce time of 400 ms:

#include <MD_UISwitch.h>

// Define what type of testing is being done
#define TEST_DIGITAL_SIMPLE 1

#if TEST_DIGITAL_SIMPLE
#define TITLE "Simple Digital"

const uint8_t DIGITAL_SWITCH_PIN = 2;       // switch connected to this pin
const uint8_t DIGITAL_SWITCH_ACTIVE = LOW;  // digital signal when switch is pressed 'on'

MD_UISwitch_Digital S(DIGITAL_SWITCH_PIN, DIGITAL_SWITCH_ACTIVE);
#endif

void setup() {
  Serial.begin(57600);
  Serial.print(F("\n[MD_UISwitch "));
  Serial.print(F(TITLE));
  Serial.print(F(" Example]"));

  S.begin();
  S.enableDoublePress(false);
  S.enableLongPress(false);
  S.enableRepeat(false);
  S.enableRepeatResult(true);
  setDebounceTime(400);

}

void loop() {
  // put your main code here, to run repeatedly:
  MD_UISwitch::keyResult_t k = S.read();

  switch(k)
  {
    case MD_UISwitch::KEY_NULL:      /* Serial.println("NULL"); */  break;
    case MD_UISwitch::KEY_PRESS:     Serial.print("\nKEY_SINGLE "); break;
    case MD_UISwitch::KEY_DPRESS:    Serial.print("\nKEY_DOUBLE "); break;
    case MD_UISwitch::KEY_LONGPRESS: Serial.print("\nKEY_LONG   "); break;
    case MD_UISwitch::KEY_RPTPRESS:  Serial.print("\nKEY_REPEAT "); break;
    default:                         Serial.print("\nKEY_UNKNWN "); break;
  }
  if (k != MD_UISwitch::KEY_NULL)
  {
    if (S.getKey() >= ' ')
    {
      Serial.print((char)S.getKey());
      Serial.print(" ");
    }
    Serial.print("[0x");
    Serial.print(S.getKey(), HEX);
    Serial.print("]");
  }

}
MajicDesigns commented 6 years ago

Bounce is unwanted mechanical switching that occurs when a physical contactor moves from one state to another. The debounce time is a short time that allows the MCU to ignore the intermediate switching, thus eliminating the potential to detect multiple ACTIVE/INACTIVE transitions during the bounce period.

The actual switch 'pressed' detection occurs when the first transition of INACTIVE to ACTIVE switch states is detected, irrespective of the debounce time.