-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDebouncedSwitch.cpp
More file actions
64 lines (52 loc) · 1.7 KB
/
DebouncedSwitch.cpp
File metadata and controls
64 lines (52 loc) · 1.7 KB
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
#include "DebouncedSwitch.h"
void DebouncedSwitch::_init (byte pin_number, uint8_t pin_mode) {
_pin_number = pin_number;
pinMode(_pin_number, pin_mode);
_on_switch_close_callback = NULL;
_on_switch_open_callback = NULL;
_first_trigger = 0;
closed = digitalRead(_pin_number) != _closed_state;
};
DebouncedSwitch::DebouncedSwitch (byte pin_number, uint8_t pin_mode) {
_closed_state = HIGH;
_init(pin_number, pin_mode);
};
DebouncedSwitch::DebouncedSwitch (byte pin_number, uint8_t pin_mode, uint8_t closed_state) {
_closed_state = closed_state;
_init(pin_number, pin_mode);
};
void DebouncedSwitch::attachOnSwitchCloseCallback (SwitchCallback callback) {
_on_switch_close_callback = callback;
};
void DebouncedSwitch::attachOnSwitchOpenCallback (SwitchCallback callback) {
_on_switch_open_callback = callback;
};
void DebouncedSwitch::update () {
if (closed ?
digitalRead(_pin_number) == _closed_state :
digitalRead(_pin_number) != _closed_state
) {
if (!_first_trigger) {
_first_trigger = millis();
if (closed) {
if (_on_switch_open_callback != NULL) {
(*_on_switch_open_callback)();
}
}
else {
if (_on_switch_close_callback != NULL) {
(*_on_switch_close_callback)();
}
}
}
if (millis() - _first_trigger > DEBOUNCED_SWITCH_DEBOUNCE_INTERVAL) {
closed = !closed;
_first_trigger = 0;
}
}
else {
if (millis() - _first_trigger > DEBOUNCED_SWITCH_DEBOUNCE_INTERVAL) {
_first_trigger = 0;
}
}
};