-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathButton.cpp
More file actions
120 lines (100 loc) · 2.21 KB
/
Button.cpp
File metadata and controls
120 lines (100 loc) · 2.21 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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
/*
* Hardware::Button - Library for detecting button clicks, multiple clicks and long press on a button for use with the Arduino environment.
* Copyright (c) by Andrii Tishchenko, 2016
* This work is licensed under a BSD style license.
* https://github.com/andriitishchenko/HardwareButton
*/
#include "Button.h"
namespace Hardware
{
void Button::init(int pin, int activeLow) {
pinMode(pin, INPUT);
_pin = pin;
_pressTimeout = 600;
_longPressTimeout = 1000;
_multiPressTimeout = 260;
isPressed = false;
if (activeLow) {
_buttonReleased = HIGH;
_buttonPressed = LOW;
digitalWrite(pin, HIGH);
} else {
_buttonReleased = LOW;
_buttonPressed = HIGH;
} // if
onPress = NULL;
onLongPress = NULL;
onLongPressing = NULL;
onMultiplePress = NULL;
}
Button::Button(int pin) {
this->init(pin, false);
}
Button::Button(int pin, int activeLow)
{
this->init(pin, activeLow);
} // Button
void Button::setPressTimeout(int value) {
_pressTimeout = value;
}
void Button::setLongPressTimeout(int value) {
_longPressTimeout = value;
}
void Button::setMultiPressTimeout(int value) {
_multiPressTimeout = value;
}
void Button::update(void)
{
int pinState = digitalRead(_pin);
ulong now = millis();
if (pinState == _buttonPressed) {
if (_startTime != 0)
{
if ((ulong)(now - _startTime) > _pressTimeout) { //holding button
if (onLongPressing) onLongPressing(*this);
}
}
else {
_startTime = now;
}
isPressed = true;
}
else if (_startTime != 0) {
if ((ulong)(now - _startTime) > _longPressTimeout) //button released
{
_releaseTime = 0;
if (onLongPress) onLongPress(*this);
}
else {
//expectng multipress:
if (_releaseTime != 0)
{
pressCount++;
}
else
{
pressCount = 1;
}
_releaseTime = now;
}
_startTime = 0;
isPressed = false;
}
if (_releaseTime != 0)
{
if ( (ulong)(now - _releaseTime) > _multiPressTimeout)
{
if (pressCount == 1)
{
if (onPress) onPress(*this);
}
else
{
if (onMultiplePress) onMultiplePress(*this);
}
_releaseTime = 0;
_startTime = 0;
}
}
}
}