-
Notifications
You must be signed in to change notification settings - Fork 0
/
AutoSwitch.cpp
64 lines (51 loc) · 1.18 KB
/
AutoSwitch.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
/*
AutoSwitch - a button with automatic off timer
created 8 Nov 2017
by Bence Meszaros
*/
#include "Arduino.h"
#include "AutoSwitch.h"
AutoSwitch::AutoSwitch()
{
this->state = LOW;
this->debounce = 200;
this->debounceTimer = 0;
}
AutoSwitch::AutoSwitch(int pin, unsigned long autoOff)
: AutoSwitch()
{
this->setPin(pin);
this->setAutoOff(autoOff);
}
AutoSwitch& AutoSwitch::setPin(int pin)
{
this->pin = pin;
pinMode(this->pin, INPUT_PULLUP);
return *this;
}
AutoSwitch& AutoSwitch::setAutoOff(unsigned long time)
{
this->autoOff = time * 1000;
return *this;
}
int AutoSwitch::getState()
{
int newState = digitalRead(this->pin);
// check state change
if (this->oldState != newState && millis() - this->debounceTimer > this->debounce) {
if (newState == LOW) {
this->state = !this->state;
if (this->autoOff > 0) {
this->autoOffTimer = millis();
}
this->debounceTimer = millis();
}
this->oldState = newState;
}
// check auto off
if (this->autoOffTimer > 0 && millis() - this->autoOffTimer >= this->autoOff) {
this->state = LOW;
this->autoOffTimer = 0;
}
return this->state;
}