Complete rewrite of Application
This commit is contained in:
62
Button.cpp
Normal file
62
Button.cpp
Normal file
@@ -0,0 +1,62 @@
|
||||
#include "Button.h"
|
||||
|
||||
Button::Button(uint8_t pin)
|
||||
: pin(pin),
|
||||
stableState(HIGH),
|
||||
lastReading(HIGH),
|
||||
prevStableState(HIGH),
|
||||
lastDebounceTime(0),
|
||||
pressStart(0) {}
|
||||
|
||||
void Button::begin() {
|
||||
pinMode(pin, INPUT_PULLUP);
|
||||
|
||||
stableState = digitalRead(pin);
|
||||
lastReading = stableState;
|
||||
prevStableState = stableState;
|
||||
|
||||
lastDebounceTime = millis();
|
||||
|
||||
if (stableState == LOW) {
|
||||
pressStart = millis();
|
||||
}
|
||||
}
|
||||
|
||||
void Button::update(unsigned long now) {
|
||||
prevStableState = stableState;
|
||||
|
||||
bool reading = digitalRead(pin);
|
||||
|
||||
if (reading != lastReading) {
|
||||
lastDebounceTime = now;
|
||||
lastReading = reading;
|
||||
}
|
||||
|
||||
if ((now - lastDebounceTime) > debounceDelay) {
|
||||
if (stableState != reading) {
|
||||
stableState = reading;
|
||||
|
||||
// Button just became pressed (active LOW)
|
||||
if (stableState == LOW) {
|
||||
pressStart = now;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
bool Button::pressed() {
|
||||
return (prevStableState == HIGH && stableState == LOW);
|
||||
}
|
||||
|
||||
bool Button::released() {
|
||||
return (prevStableState == LOW && stableState == HIGH);
|
||||
}
|
||||
|
||||
bool Button::isDown() {
|
||||
return stableState == LOW;
|
||||
}
|
||||
|
||||
bool Button::held(unsigned long ms) {
|
||||
if (!isDown()) return false;
|
||||
return (millis() - pressStart >= ms);
|
||||
}
|
||||
Reference in New Issue
Block a user