-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathTouchPin.cpp
163 lines (119 loc) · 2.3 KB
/
TouchPin.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
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
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
#include "Arduino.h"
#include "TouchPin.h"
#include "InterruptGuard.h"
#define MAX(a,b) ((a)>(b)?(a):(b))
#define SCALE( offset ) (offset)
#define HYSTERESIS( offset ) MAX( (offset)/2, 5 )
const int CALIBRATION_RUNS = 16,
MEASURE_RUNS = 4
;
const int MIN_CLICK = 50,
MIN_HOLD = 200,
MIN_PUSH = 50; //ms
TouchPin::TouchPin( int pin )
{
_pin = pin;
_offset = 0;
_touchStart = 0;
_hysteresis = 0;
_pushed = false;
pinMode( _pin, INPUT );
}
int TouchPin::_read()
{
register int count = 0;
{
InterruptGuard g();
pinMode( _pin, OUTPUT );
digitalWrite( _pin, 1 );
pinMode( _pin, INPUT );
while( digitalRead( _pin ) ){
count++;
}
}
return count;
}
#pragma GCC push_options
#pragma GCC optimize ("unroll-loops")
int TouchPin::calibrate()
{
register int i;
int sum = 0,
offset;
for( i = 0; i < CALIBRATION_RUNS; i++ ) {
sum += _read();
}
offset = sum / CALIBRATION_RUNS;
_offset = offset;
_hysteresis = HYSTERESIS( offset );
_scale = SCALE( offset );
return _offset;
}
int TouchPin::read()
{
register int i;
int result=0;
for( i=0; i<MEASURE_RUNS; i++ ) {
result += _read() - _offset;
}
result /= MEASURE_RUNS;
if( result < 0 ) result = 0;
if( result ) _lastCount = result;
return result;
}
#pragma GCC pop_options
long TouchPin::_touchTime()
{
unsigned long now = millis(),
result = 0
;
bool touching;
if( _touchStart ) {
result = now - _touchStart;
}
touching = isTouch();
if( touching && !_touchStart ) _touchStart = now;
else if( !touching ) _touchStart = 0;
return touching ? result : -result;
}
bool TouchPin::isTouch()
{
int value = read();
return value >= _hysteresis;
}
bool TouchPin::isClick()
{
long touchTime = _touchTime();
return touchTime < -MIN_CLICK;
}
bool TouchPin::isHold()
{
long touchTime = _touchTime();
return touchTime > MIN_HOLD;
}
bool TouchPin::isPush()
{
long touchTime = _touchTime();
if( touchTime > MIN_PUSH ) {
if( ! _pushed ){
_pushed = true;
return true;
}
} else {
_pushed = false;
}
return false;
}
int TouchPin::strength()
{
return _lastCount / _scale;
}
void TouchPin::printInfo()
{
Serial.print( "Pin: " );
Serial.print( _pin );
Serial.print( "Offset: " );
Serial.print( _offset );
Serial.print( "Hysteresis: " );
Serial.println( _hysteresis );
}