-
Notifications
You must be signed in to change notification settings - Fork 1
/
ToggleSwitch.cpp
56 lines (44 loc) · 1.12 KB
/
ToggleSwitch.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
#include "ToggleSwitch.h"
#define ToggleSwitchChangeResiliency 5
ToggleSwitch::ToggleSwitch(uint8_t pin) :ToggleSwitch(pin, LOW)
{ }
ToggleSwitch::ToggleSwitch(uint8_t pin, uint8_t closedState)
{
this->_pin = pin;
this->_closedState = closedState;
this->_pastReadings = 0;
pinMode(this->_pin, INPUT_PULLUP);
CallbackSetup callbackRequest((void*)this, &ToggleSwitch::UpdateCallbackWrapper);
CpuSpinner::RequestUpdate(callbackRequest);
}
void ToggleSwitch::Update() {
if (digitalRead(this->_pin) == this->_closedState) {
this->ClosedStateDetected();
}
else {
this->OpenedStateDetected();
}
}
bool ToggleSwitch::IsClosed()
{
if (this->_pastReadings == 0)
this->Update();
return this->_pastReadings > 0;
}
void ToggleSwitch::UpdateCallbackWrapper(void *instance)
{
ToggleSwitch* self = (ToggleSwitch*)instance;
self->Update();
}
void ToggleSwitch::ClosedStateDetected()
{
if (this->_pastReadings == ToggleSwitchChangeResiliency)
return;
this->_pastReadings += 1;
}
void ToggleSwitch::OpenedStateDetected()
{
if (this->_pastReadings == ToggleSwitchChangeResiliency*(-1))
return;
this->_pastReadings -= 1;
}