-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathButton.cpp
More file actions
44 lines (37 loc) · 927 Bytes
/
Button.cpp
File metadata and controls
44 lines (37 loc) · 927 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
#include "Button.h"
#define BUTTON_DEBOUNCE_MILLIS 50UL
Button::Button(byte pin) {
this->pin = pin;
}
void Button::onInterrupt(void (*buttonIsr)(void)) {
pinMode(pin, INPUT_PULLUP);
attachInterrupt(digitalPinToInterrupt(pin), buttonIsr, CHANGE);
}
void Button::onPressed(void (*onPressedCallback)(void)) {
this->onPressedCallback = onPressedCallback;
}
boolean Button::read() {
noInterrupts();
const boolean lastPressed = pressed;
if (lastPressed) {
pressed = false;
}
interrupts();
if (lastPressed && onPressedCallback) {
onPressedCallback();
}
return lastPressed;
}
unsigned long Button::getLastPressedAtTimestamp() {
noInterrupts();
unsigned long v = lastPressedAtTimestamp;
interrupts();
return v;
}
void Button::isr() {
unsigned long now = millis();
if (now - lastPressedAtTimestamp > BUTTON_DEBOUNCE_MILLIS) {
lastPressedAtTimestamp = now;
pressed = true;
}
}