Show a pusbutton "bounciness"...

Hi, I have a dfrobot "joystick + 3 pushbuttons" shield, and I wanted to count the number of bounces I get when pushing each of the three buttons.

When used with the dfrobot shield I mentioned, this code show the number of bounces of the joystick button.

Change btnPin value to taste.

/*
 * Test a pushbutton "bounciness".
 *
 * Connect a pushbutton to pin 5.
 * Open serial monitor.
 * Push the button and see the transition count
 * on the serial monitor.
 * It should read 2 (press + release),
 * but because of the "bounce" problem, the number of
 * transisions can be 4, 6 or even higher.
 *
 */

int btnPin = 5;
int btn;
int prevBtn;
long cnt = 0;
long prevMillis;


void setup() {
    Serial.begin(115200);

    pinMode(btnPin, INPUT);
    btn = digitalRead(btnPin);
    prevBtn = btn;
}


void loop() {
    btn = digitalRead(btnPin);
    
    if (btn != prevBtn) {
        prevBtn = btn;
        cnt++;
        prevMillis = millis();
    }
    
    if (millis() - prevMillis > 2000) {
        prevMillis = millis();
        Serial.println(cnt);
        cnt = 0;
    }
}

Simple, but useful :).

I used it to test the quality of my tactile buttons. All of them only registered 2 transitions :).

Thanks. I'm glad it's useful.

In my DFRobot shield the two "proper" pushbuttons registered 2 (rarely 4) transisions. The button under the joystick, instead, gave 4 to 16 transitions!