forked from earlephilhower/psychoplug
-
Notifications
You must be signed in to change notification settings - Fork 0
/
button.cpp
89 lines (74 loc) · 2.28 KB
/
button.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
/*
PsychoPlug
ESP8266 based remote outlet with standalone timer and MQTT integration
Copyright (C) 2017 Earle F. Philhower, III
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "psychoplug.h"
#include "button.h"
#include "settings.h"
#include "mqtt.h"
#include "relay.h"
#include "log.h"
static byte DebounceButton();
#define PIN_BUTTON (13)
void StartButton()
{
pinMode(PIN_BUTTON, INPUT_PULLUP);
}
// Hendle all power button management (debounce, mqtt, etc.)
void ManageButton()
{
// Let the button toggle the relay always
byte action = DebounceButton();
if (action==BUTTON_PRESS) {
SetRelay(!GetRelay());
}
if (action != BUTTON_NONE) {
MQTTPublish("button", action==BUTTON_PRESS?"press":"release");
}
}
bool RawButton()
{
return !digitalRead(PIN_BUTTON);
}
// Check if button has been pressed (after debounce) and return one event for press and one for release
static byte DebounceButton()
{
static bool ignoring = false;
static unsigned long checkTime = 0;
static bool prevButton = false;
static bool debounceButton = false;
byte event = BUTTON_NONE;
if (!ignoring) {
bool curButton = !digitalRead(PIN_BUTTON);
if (curButton != prevButton) {
ignoring = true;
checkTime = micros() + 5000;
}
prevButton = curButton;
} else {
bool curButton = !digitalRead(PIN_BUTTON);
if (curButton != prevButton) {
// Noise, reset the clock
ignoring = false;
} else if (micros() > checkTime) {
if (curButton != debounceButton) {
event = (debounceButton)?BUTTON_RELEASE:BUTTON_PRESS;
debounceButton = curButton;
LogPrintf("Button Event: %d\n", event);
}
ignoring = false;
}
}
return event;
}