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;
}
}