Skip to content

Instantly share code, notes, and snippets.

@hollance
Created December 24, 2020 14:45
Show Gist options
  • Save hollance/511d1f2c805afbd12d9ca6b2add36298 to your computer and use it in GitHub Desktop.
Save hollance/511d1f2c805afbd12d9ca6b2add36298 to your computer and use it in GitHub Desktop.
Arduino push button debouncing
#include "Button.h"
Button::Button() : _pin(0), _oldState(0) {
}
void Button::attach(byte pin) {
_pin = pin;
pinMode(_pin, INPUT);
}
byte Button::debounce() {
byte state = digitalRead(_pin);
if (state != _oldState) {
delay(5);
state = digitalRead(_pin); // read again
}
return state;
}
boolean Button::isPressed() {
byte state = debounce();
boolean pressed = (!_oldState && state);
_oldState = state;
return pressed;
}
#ifndef BUTTON_H
#define BUTTON_H
#include <Arduino.h>
/*
Simple class for a push button.
How to use:
Button button;
void setup() {
button.attach(somePin);
}
void loop() {
if (button.isPressed()) {
// do something
}
}
*/
class Button {
public:
Button();
void attach(byte pin);
boolean isPressed();
private:
byte debounce();
byte _pin;
byte _oldState;
};
#endif // BUTTON_H
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment