forked from justcallmekoko/ESP32Marauder
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSwitches.cpp
98 lines (81 loc) · 1.8 KB
/
Switches.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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
#include "Switches.h"
Switches::Switches() {
this->pin = 0;
this->pin = false;
this->pressed = false;
this->hold_lim = 2000;
this->cur_hold = 0;
this->isheld = false;
pinMode(this->pin, INPUT);
return;
}
Switches::Switches(int pin, uint32_t hold_lim, bool pullup) {
this->pin = pin;
this->pullup = pullup;
this->pressed = false;
this->hold_lim = hold_lim;
this->cur_hold = 0;
this->isheld = false;
if (pullup)
pinMode(this->pin, INPUT_PULLUP);
else
pinMode(this->pin, INPUT_PULLDOWN);
return;
}
int Switches::getPin() {
return this->pin;
}
bool Switches::getPullup() {
return this->pullup;
}
bool Switches::isHeld() {
return this->isheld;
}
bool Switches::getButtonState() {
int buttonState = digitalRead(this->pin);
if ((this->pullup) && (buttonState == LOW))
return true;
else if ((!this->pullup) && (buttonState == HIGH))
return true;
else
return false;
}
bool Switches::justPressed() {
bool btn_state = this->getButtonState();
// Button was JUST pressed
if (btn_state && !this->pressed) {
this->hold_init = millis();
this->pressed = btn_state;
return true;
}
else if (btn_state) { // Button is STILL pressed
// Check if button is held
//Serial.println("cur_hold: " + (String)this->cur_hold);
if ((millis() - this->hold_init) < this->hold_lim) {
this->isheld = false;
}
else {
this->isheld = true;
}
this->pressed = btn_state;
return false;
}
else { // Button is not pressed
this->pressed = btn_state;
this->isheld = false;
return false;
}
}
bool Switches::justReleased() {
bool btn_state = this->getButtonState();
// Button was JUST released
if (!btn_state && this->pressed) {
this->isheld = false;
this->pressed = btn_state;
return true;
}
else { // Button is STILL released
this->pressed = btn_state;
return false;
}
}