/
xpt2046.c
555 lines (478 loc) · 12.5 KB
/
xpt2046.c
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
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
/**
@file xpt2046.c
@version V0.10
@date 22 Sept 2016
@brief XPT2046 drivers
@par Copyright © 2015 Mike Gore, GPL License
@par You are free to use this code under the terms of GPL
please retain a copy of this notice in any code you use it in.
This 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 software 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 <stdint.h>
#include <stdarg.h>
#include <string.h>
#include <math.h>
#include "user_config.h"
#if DISPLAY
#ifdef XPT2046
#include "xpt2046.h"
#include "display/ili9341.h"
/// =============================================================
/// =============================================================
/// HAL
extern window *tft;
#ifndef XPT2046_CS
#error You must define the XPT2046 GPIO pin
#endif
/// Start SPI Hardware Abstraction Layer
/// Keep all hardware dependent SPI code in this section
/// @brief cache of SPI clock devisor
uint32_t XPT2046_clock = -1;
///@breif touch event queue
xpt2046_t xpt2046;
/// @brief Obtain SPI bus for XPT2046, raises LE
/// return: void
MEMSPACE
void XPT2046_spi_init(void)
{
XPT2046_clock = 40;
chip_select_init(XPT2046_CS);
XPT2046_key_flush();
xpt2046.rotation = tft->rotation;
}
/// @brief reset key press touch queue
MEMSPACE
void XPT2046_key_flush()
{
xpt2046.state = 0;
xpt2046.ms = 0;
xpt2046.ind = 0;
xpt2046.head = 0;
xpt2046.tail = 0;
}
/**
Command byte mode bits used in this project
Lower Command Nibble (4 bits) for this project
Note:
/DFR = 0 is differential mode
Ratiometric conversion - has lowest noise for ADC readings
PD1 = 0 turns off reference, required for this mode (/DFR=0)
PD0 = 1 enable ADC
PD0 = 0 power down device
MODE = 0 12 bits
Summary for lower nibble, we only use:
MODE SER//DFR PD1 PD0
0 0 0 0 12bit, /DFR, REF off, ADC off
0 0 0 1 12bit, /DFR, REF off, ADC on
Upper Command Nibble (4 bits) for this project
Note:
S = 1 Command byte
S = 0 read data used to clock out data after first command byte
Summary for upper nibble, we only use
S A2 A1 A0 ADC+IN MEASUREMENT DRIVERS
1 0 0 0 TEMP0
1 0 0 1 XP Y-POS YN YP
1 0 1 0 VBAT
1 0 1 1 XP Z1-POS XN YP
1 1 0 0 YN Z2-POS XN YP
1 1 0 1 YP X-POS XN XP
1 1 1 0 AUXIN
1 1 1 1 TEMP
We only need 4 commands for reading position or touch information
0x91 Read Y position
0xb1 Read Z1
0xc1 Read Z2
0xd1 Read X position
*/
/// @brief Send command and read ADC result
/// @param[in] cmd: command byte
/// return: ADC value
uint16_t XPT2046_read(uint8_t cmd)
{
uint8_t buf[3];
uint16_t val;
// First byte to send is the command
buf[0] = cmd;
// 0 is ignored as a command NOOP, used here to read the reply from the ADC
buf[1] = 0;
buf[2] = 0;
spi_begin(XPT2046_clock, XPT2046_CS);
// Send three bytes and read the result
spi_TXRX_buffer(buf,3);
spi_end(XPT2046_CS);
// buf[0] - Ignore data read back from the first command byte - is has no valid data
// Extract the ADC 12 bit reply - ADC result starts one bit AFTER the MSB bit position
val = buf[1]; // MSB
val <<= 8;
val |= buf[2]; // LSB
// Align 12 bit result to LSB bit position
val >>= 3;
if(val < 0)
val = 0;
if(val >4095)
val = 4095;
return(val);
}
/// @brief Check touch state and return the X,Y value if true
/// NO filtereing is done - use XPT2046_xy_filtered if you need filtering
/// @param[out] *X: X value
/// @param[out] *Y: Y value
/// return: Touch state 1 = touch, 0 = no touch
//MEMSPACE
int XPT2046_xy_raw(uint16_t *X, uint16_t *Y)
{
int Z1,Z2,Z;
Z1 = XPT2046_read(XPT2046_READ_Z1);
Z2 = XPT2046_read(XPT2046_READ_Z2);
// of the touch pressure
Z = (4095 - Z2) + Z1;
if(Z < 0)
Z = -Z;
if(Z > 300)
{
switch (tft->rotation)
{
case 0:
// reverse X
xpt2046.rotation = 0;
*X = 4095 - XPT2046_read(XPT2046_READ_X);
*Y = XPT2046_read(XPT2046_READ_Y);
break;
case 1:
// swap X and Y
xpt2046.rotation = 1;
*X = XPT2046_read(XPT2046_READ_Y);
*Y = XPT2046_read(XPT2046_READ_X);
break;
case 2:
// reverse Y
xpt2046.rotation = 2;
*X = XPT2046_read(XPT2046_READ_X);
*Y = 4095 - XPT2046_read(XPT2046_READ_Y);
break;
case 3:
xpt2046.rotation = 3;
// swap X and Y and reverse X and Y
*X = 4095 - XPT2046_read(XPT2046_READ_Y);
*Y = 4095 - XPT2046_read(XPT2046_READ_X);
break;
}
return(1); // 1 = touch event
}
return(0); // no touch event
}
#if 0
/// @brief Check Touch state - if touched then average a set of X and Y readings
/// Check at most XPT2046_SAMPLES that are within noise limits
/// @param[out] *X: X position - ONLY if touched
/// @param[out] *Y: Y position - ONLY if touched
/// return: count of consecutive samples within noise limits - or 0 if not touched.
/// Ideally we want count to be at least >= XPT2046_SAMPLES/2
MEMSPACE
int XPT2046_xy_filtered(uint16_t *X, uint16_t *Y)
{
int XC,YC, XL,YL, XD, YD;
long Xavg,Yavg;
int count; // Sample counter - to compute average
Xavg = 0; // X average
Yavg = 0; // Y average
for(count=0;count<XPT2046_SAMPLES;++count)
{
// X and Y if touched - otherwise 0,0
if(!XPT2046_xy_raw(X, Y))
break;
XC = *X;
YC = *Y;
// Has the permitted peak to peak NOISE maximum been exceeded ?
if(count)
{
XD = XC - XL;
if(XD < 0)
XD = -XD;
YD = YC - YL;
if(YD < 0)
YD = -YD;
if(XD > 20 || YD > 20)
break;
}
// Update average
Xavg += XC;
Yavg += YC;
XL = XC;
YL = YC;
}
// FIXME testing shows we need at least 2 samples in a row to be ok
if(count)
{
Xavg /= count;
Yavg /= count;
}
*X = (uint16_t) Xavg;
*Y = (uint16_t) Yavg;
return(count);
}
#else
/// @brief Calculates best average of longest run
/// Where longest run is calculated using best running average of absolute differences (noise)
/// @param[int] *v: integer array
/// @param[int] size: size of array
/// @param[int] minsamples: minimum number samples required for valid result
/// return: average of longest run or -1 if limits not met
int XPT2046_loop;
MEMSPACE
int nearest_run(int *v, int size, int minsamples, int *count)
{
int i,j;
int val;
int diff,diffavg;
int run;
int sum;
int noise;
int min_run = 1;
int average = 0;
int min_noise = 65536;
for(i=0;i<size;++i)
{
val = v[i];
sum = val;
run = 0;
noise = 0;
for(j=i+1;j<size;++j)
{
// compute differences
diff = v[j] - val;
if(diff < 0)
diff = -diff;
++run;
// this is run+1 sample we have averaged
sum += v[j];
noise += diff;
// FIXME we want average signal to noise ratio
// always favor longer runs if better or equal noise
if(run >= minsamples)
{
if((noise/run) <= min_noise/min_run)
{
min_noise = noise;;
min_run = run;
// we have run + 1 elements
average = sum/(run+1);
}
}
}
}
// we have run + 1 elements
*count = min_run+1;
if(min_run >= minsamples)
{
return(average);
}
return(-1);
}
/// @brief Check Touch state - if touched then average a set of X and Y readings
/// Check at most XPT2046_SAMPLES that are within noise limits
/// @param[out] *X: X position - ONLY if touched
/// @param[out] *Y: Y position - ONLY if touched
/// return: count of consecutive samples within noise limits - or 0 if not touched.
/// Ideally we want count to be at least >= XPT2046_SAMPLES/2
MEMSPACE
int XPT2046_xy_filtered(uint16_t *X, uint16_t *Y)
{
int XS[XPT2046_SAMPLES+1];
int YS[XPT2046_SAMPLES+1];
int Xavg,Yavg;
int xcount,ycount;
int i;
for(i=0;i<XPT2046_SAMPLES;++i)
{
// X and Y if touched - otherwise 0,0
if(!XPT2046_xy_raw(X, Y))
break;
XS[i] = *X;
YS[i] = *Y;
}
if(i >= 3)
{
Xavg = nearest_run((int *) &XS, i, 3, &xcount);
Yavg = nearest_run((int *) &YS, i, 3, &ycount);
if(Xavg >= 0 && Yavg >= 0)
{
*X = (uint16_t) Xavg;
*Y = (uint16_t) Yavg;
#if XPT2046_DEBUG & 2
printf("X:%4d, Y:%4d, XN:%2d, YN:%d\n",
(int)Xavg, (int)Yavg, (int)xcount,(int)ycount);
#endif
return(i);
}
}
return(0);
}
#endif
/// @brief Test XPT2046_xy_filtered() to determine how long it takes a good read of X and Y within noise limits
/// Warning: This is only used for testing because it can block for up to 100ms
/// @param[out] *X: X position - ONLY if touched
/// @param[out] *Y: Y position - ONLY if touched
/// return: 1 if touch state is true, or 0
int XPT2046_loop;
MEMSPACE
int XPT2046_xy_filtered_test(uint16_t *X, uint16_t *Y)
{
int T;
XPT2046_loop = 0;
while(1)
{
T = XPT2046_xy_filtered(X, Y);
XPT2046_loop += T;
if(!T)
return(0);
if(T >= XPT2046_SAMPLES/2)
return(1);
}
}
/// @brief Task to collect debounced KEY press style touch events
/// We treat the touch screen as a keyboard with debounce processing
/// return: void
MEMSPACE
void XPT2046_task()
{
uint16_t X,Y;
int T;
T = XPT2046_xy_filtered((uint16_t *)&X, (uint16_t *)&Y);
// Key debounce state machine
switch(xpt2046.state)
{
// Full init
case 0:
xpt2046.state = 1;
xpt2046.ms = 0;
xpt2046.ind = 0;
xpt2046.head = 0;
xpt2046.tail = 0;
// Fall through to state 1
case 1:
// FIXME this can be a lower count for a button as we are not drawing here
if(T) // key is down and noise level is in range
{
// wait for key down debounce time before taking a sample
if(++xpt2046.ms < XPT2046_DEBOUNCE)
break;
if(xpt2046.ind < XPT2046_EVENTS )
{
xpt2046.XQ[xpt2046.head] = X;
xpt2046.YQ[xpt2046.head] = Y;
if(++xpt2046.head >= XPT2046_EVENTS)
xpt2046.head = 0;
xpt2046.ind++;
xpt2046.state = 2;
xpt2046.ms = 0;
}
else
{
xpt2046.ms = 0;
}
} // if (T)
else // Restart timer and wait for touch debounce time
{
xpt2046.ms = 0;
}
break;
// Wait for touch release debounce time
case 2:
// Released ?
if(T == 0)
{
// Debounce release time - valid key depress cycle done
if(++xpt2046.ms >= XPT2046_DEBOUNCE)
{
xpt2046.ms = 0;
xpt2046.state = 1;
}
}
else // Still depressed
{
xpt2046.ms = 0;
}
break;
// Error INIT
default:
xpt2046.state = 0;
break;
}
}
/// @brief return uncalibrated key press
/// @param[in] *X: X position
/// @param[in] *Y: Y position
/// return: 1 on touch event in queue
MEMSPACE
int XPT2046_key(uint16_t *X, uint16_t *Y)
{
XPT2046_task();
if(xpt2046.ind > 0)
{
*X = (uint16_t) xpt2046.XQ[xpt2046.tail];
*Y = (uint16_t) xpt2046.YQ[xpt2046.tail];
if(++xpt2046.tail >= XPT2046_EVENTS)
xpt2046.tail = 0;
xpt2046.ind--;
return(1);
}
*X = 0;
*Y = 0;
return(0);
}
// ===========================================================================
//
#ifdef ESP8266
int __errno;
#endif
///@brief For noise filtering we can use the standard deviation of a set of samples
/// Then we can reject samples outside of say +/- 1 standard deviation in the set
/// Sample size MUST be 2 or greater, this is by definition of the term standard deviation
/// @param[in] *sample: array of uint16_t samples
/// @param[in] size: number of samples
/// @param[out] *Z: sdev_t * structure pointer to computer results into
/// @return 1 on success, 0 on parameter or calculation error
MEMSPACE
int sdev(uint16_t *samples, int size, sdev_t *Z)
{
int i;
float val, delta, sum, sqsum;
Z->min = ~0;
Z->max = 0;
// error in sample size ?
if(size < 2)
return(0);
sum = 0.0;
for(i=0; i<size ; i++) {
val = samples[i];
if(Z->min > val)
Z->min = val;
if(Z->max < val)
Z->max = val;
sum += val;
}
Z->mean = sum / (float) size;
sqsum = 0.0;
for(i=0;i<size;++i) {
val = samples[i];
if(val < 0 || val > 4095)
continue; // reject
delta = val - Z->mean;
sqsum += (delta * delta);
}
val = sqsum / (float) (i - 1);
Z->sdev = sqrt(val);
return(1);
}
#endif // XPT2046
#endif // DISPLAY