Perehama:
/* The Push-button example I wish I had when I started
- by Perehama, credit to PieterP for the push-button class idea
*/
class IntervalTimer {
public:
IntervalTimer(unsigned long i);
void synchronizeTimer();
bool intervalComplete();
void setInterval(unsigned long i);
unsigned long elapsedTime();
private:
unsigned long _interval;
unsigned long _timestamp;
};
class PushButton {
public:
PushButton(byte pinNumber);
void inputPullup() const;
bool isPushed();
unsigned long durationHeld();
void setDebounce(unsigned long i);
private:
IntervalTimer _timer;
int _preState = HIGH;
byte _debounceFlag = 0;
const byte _ButtonPin;
const static int _RisingEdge = HIGH - LOW;
const static int _FallingEdge = LOW - HIGH;
};
IntervalTimer::IntervalTimer(const unsigned long i) : _interval(i) {}
void IntervalTimer::synchronizeTimer() {
_timestamp = millis();
}
bool IntervalTimer::intervalComplete() {
if (millis() - _timestamp >= _interval) {
_timestamp += _interval;
return true;
}
return false;
}
void IntervalTimer::setInterval(unsigned long i) {
_interval = i;
}
unsigned long IntervalTimer::elapsedTime() {
unsigned long x = millis() - _timestamp;
return x;
}
PushButton::PushButton(byte pinNumber) : _timer(50UL), _ButtonPin(pinNumber) { }
void PushButton::inputPullup() const {
pinMode(_ButtonPin, INPUT_PULLUP);
}
bool PushButton::isPushed() {
bool b = false;
if (_debounceFlag == 1) {
if (_timer.intervalComplete()) _debounceFlag = 0;
}
else {
int sample = digitalRead(_ButtonPin);
int state = sample - _preState;
if (state == _FallingEdge) {
_timer.synchronizeTimer();
b = true;
_debounceFlag = 1;
}
else if (state == _RisingEdge) {
_timer.synchronizeTimer();
_debounceFlag = 1;
}
_preState = sample;
}
return b;
}
unsigned long PushButton::durationHeld() {
unsigned long u = 0;
if (_preState == LOW) {
u = _timer.elapsedTime();
}
return u;
}
void PushButton::setDebounce(unsigned long i) {
_timer.setInterval(i);
}
const byte ButtonPin = 8;
const byte LedPin = LED_BUILTIN;
byte ledFlag;
PushButton Button(ButtonPin);
void setup() {
Button.inputPullup();
pinMode(LedPin, OUTPUT);
}
void loop() {
if (Button.isPushed()) {
ledFlag = (ledFlag) ? 0 : 1;
}
(ledFlag) ? digitalWrite(LedPin, HIGH) : digitalWrite(LedPin, LOW);
}
Thank you so much for posting this.
You kind of anticipated my reaction to your first post.
I went through the program.
I don't see which PIN would be assign to the push button to set its pinMode to INPUT.
Do you have the schematic that comes with this program?