-
Notifications
You must be signed in to change notification settings - Fork 0
/
Button.cpp
37 lines (33 loc) · 1.13 KB
/
Button.cpp
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
#include "Button.h"
Button::Button(uint32_t pin, void(*isr)(), volatile uint8_t* buttonEvent, String name) :
startOfEvent(0), buttonState(LOW), debounceTimeMs(10), buttonEvent(buttonEvent), pin(pin), name(name)
{
pinMode(pin, INPUT_PULLUP);
attachInterrupt(digitalPinToInterrupt(pin), isr, FALLING);
}
Button::~Button()
{
}
bool Button::pressed()
{
bool acceptedPress = false;
if(*buttonEvent)
{
uint32_t time = millis();
if(buttonState == LOW)// If this is the first event, record time and wait debounce time to determine if it is a good press.
{
startOfEvent = time;
buttonState = HIGH;
}
if((time - startOfEvent) > debounceTimeMs) // Wait debounceTimeMs and then check input state.
{
if(digitalRead(pin) == LOW) // if the line is still low, then it is an OK press, otherwise discard.
{
acceptedPress = true;
}
*buttonEvent = LOW; // Clear button event in preparation for next event.
buttonState = LOW; // Clear button state in preparation for next possible press.
}
}
return acceptedPress;
}