62 lines
1.2 KiB
C++
62 lines
1.2 KiB
C++
#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);
|
|
} |