-
Notifications
You must be signed in to change notification settings - Fork 2
/
button.h
80 lines (71 loc) · 1.68 KB
/
button.h
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
//
// Created by /u/frumperino
//
#include <Arduino.h>
#ifndef __simplebutton_h
#define __simplebutton_h
typedef void (*ButtonEH) (int, int); // id, state
class SimpleButton
{
private:
unsigned short pin : 8;
unsigned short state : 1;
unsigned short invert : 1;
unsigned short changing : 1;
unsigned short attached : 1;
char id;
ButtonEH handler = nullptr;
unsigned short debounceMS;
unsigned long tChange = 0;
public:
SimpleButton(char id, char pin, char invert, unsigned short debounceMS)
{
this->id = id;
this->invert = invert;
this->pin = pin;
this->changing = false;
this->debounceMS = debounceMS;
this->state = digitalRead(pin);
this->attached = false;
}
void attachHandler(ButtonEH handler)
{
this->handler = handler;
this->attached = true;
}
char getState()
{
return this->state;
}
void scan()
{
char newState = digitalRead(pin);
if (newState == state)
{
changing = false;
}
else
{
unsigned long tNow = millis();
if (!changing)
{
changing = true;
tChange = tNow;
}
else
{
unsigned long tD = tNow - tChange;
if (tD >= debounceMS)
{
state = newState;
changing = false;
if (attached)
{
handler(id, state ^ invert);
}
}
}
}
}
};
#endif //__simplebutton_h