IoT - Modular - Buttons.h
Jump to navigation
Jump to search
1 class PushButton {
2
3 public:
4
5 PushButton(uint8_t pin) // Constructor (executes when a PushButton object is created)
6
7 pin(pin) { // remember the push button pin
8
9 pinMode(pin, INPUT_PULLUP); // enable the internal pull-up resistor
10
11 };
12
13 bool isPressed() // read the button state check if the button has been pressed, debounce the button as well
14
15 {
16
17 bool pressed = false;
18
19 bool state = digitalRead(pin); // read the button's state
20
21 int8_t stateChange = state - previousState; // calculate the state change since last time
22
23 if (stateChange == rising) { // If the button is pressed (went from high to low)
24
25 if (millis() - previousBounceTime > debounceTime) { // check if the time since the last bounce is higher than the threshold
26
27 pressed = true; // the button is pressed
28
29 }
30
31 }
32
33 if (stateChange == falling) { // if the button is released or bounces
34
35 previousBounceTime = millis(); // remember when this happened
36
37 }
38
39 previousState = state; // remember the current state
40
41 return pressed; // return true if the button was pressed and didn't bounce
42
43 };
44
45 private:
46
47 uint8_t pin;
48
49 bool previousState = HIGH;
50
51 unsigned long previousBounceTime = 0;
52
53 const static unsigned long debounceTime = 1000;
54
55 const static int8_t rising = HIGH - LOW;
56
57 const static int8_t falling = LOW - HIGH;
58
59 };