]> git.donarmstrong.com Git - kiibohd-controller.git/blob - Scan/DPH/scan_loop.c
Updating DPH to compile with PartialLayer module
[kiibohd-controller.git] / Scan / DPH / scan_loop.c
1 /* Copyright (C) 2011-2013 by Joseph Makuch
2  * Additions by Jacob Alexander (2013-2014)
3  *
4  * This library is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU Lesser General Public
6  * License as published by the Free Software Foundation; either
7  * version 3.0 of the License, or (at your option) any later version.
8  *
9  * This library is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
12  * Lesser General Public License for more details.
13  *
14  * You should have received a copy of the GNU Lesser General Public
15  * License along with this library.  If not, see <http://www.gnu.org/licenses/>.
16  */
17
18 // ----- Includes -----
19
20 // Compiler Includes
21 #include <Lib/ScanLib.h>
22
23 // Project Includes
24 #include <cli.h>
25 #include <led.h>
26 #include <macro.h>
27 #include <print.h>
28
29 // Local Includes
30 #include "scan_loop.h"
31
32
33
34 // ----- Defines -----
35
36 // TODO dfj defines...needs commenting and maybe some cleaning...
37 #define MAX_PRESS_DELTA_MV 450 // As measured from the Teensy ADC pin
38 #define THRESHOLD_MV (MAX_PRESS_DELTA_MV >> 1)
39 //(2560 / (0x3ff/2)) ~= 5
40 #define MV_PER_ADC 5
41 #define THRESHOLD (THRESHOLD_MV / MV_PER_ADC)
42
43 #define STROBE_SETTLE 1
44
45 #define ADHSM 7
46
47 // Right justification of ADLAR
48 #define ADLAR_BITS 0
49
50 // full muxmask
51 #define FULL_MUX_MASK ((1 << MUX0) | (1 << MUX1) | (1 << MUX2) | (1 << MUX3) | (1 << MUX4))
52
53 // F0-f7 pins only muxmask.
54 #define MUX_MASK ((1 << MUX0) | (1 << MUX1) | (1 << MUX2))
55
56 // Strobe Masks
57 #define D_MASK (0xff)
58 #define E_MASK (0x03)
59 #define C_MASK (0xff)
60
61 // set ADC clock prescale
62 #define PRESCALE_MASK ((1 << ADPS0) | (1 << ADPS1) | (1 << ADPS2))
63 #define PRESCALE_SHIFT (ADPS0)
64 #define PRESCALE 3
65
66 // Max number of strobes supported by the hardware
67 // Strobe lines are detected at startup, extra strobes cause anomalies like phantom keypresses
68 #define MAX_STROBES 18
69
70 // Number of consecutive samples required to pass debounce
71 #define DEBOUNCE_THRESHOLD 5
72
73 // Scans to remain idle after all keys were release before starting averaging
74 // XXX So this makes the initial keypresses fast,
75 //      but it's still possible to lose a keypress if you press at the wrong time -HaaTa
76 #define KEY_IDLE_SCANS 30000
77
78 // Total number of muxes/sense lines available
79 #define MUXES_COUNT 8
80 #define MUXES_COUNT_XSHIFT 3
81
82 // Number of warm-up loops before starting to scan keys
83 #define WARMUP_LOOPS ( 1024 )
84 #define WARMUP_STOP (WARMUP_LOOPS - 1)
85
86 #define SAMPLE_CONTROL 3
87
88 #define KEY_COUNT ((MAX_STROBES) * (MUXES_COUNT))
89
90 #define RECOVERY_CONTROL 1
91 #define RECOVERY_SOURCE  0
92 #define RECOVERY_SINK    2
93
94 #define ON  1
95 #define OFF 0
96
97 // mix in 1/4 of the current average to the running average. -> (@mux_mix = 2)
98 #define MUX_MIX 2
99
100 #define IDLE_COUNT_SHIFT 8
101
102 // av = (av << shift) - av + sample; av >>= shift
103 // e.g. 1 -> (av + sample) / 2 simple average of new and old
104 //      2 -> (3 * av + sample) / 4 i.e. 3:1 mix of old to new.
105 //      3 -> (7 * av + sample) / 8 i.e. 7:1 mix of old to new.
106 #define KEYS_AVERAGES_MIX_SHIFT 3
107
108
109
110 // ----- Macros -----
111
112 // Select mux
113 #define SET_FULL_MUX(X) ((ADMUX) = (((ADMUX) & ~(FULL_MUX_MASK)) | ((X) & (FULL_MUX_MASK))))
114
115
116
117 // ----- Function Declarations -----
118
119 // CLI Functions
120 void cliFunc_avgDebug   ( char* args );
121 void cliFunc_echo       ( char* args );
122 void cliFunc_keyDebug   ( char* args );
123 void cliFunc_pressDebug ( char* args );
124 void cliFunc_problemKeys( char* args );
125 void cliFunc_senseDebug ( char* args );
126
127 // Debug Functions
128 void dumpSenseTable();
129
130 // High-level Capsense Functions
131 void setup_ADC();
132 void capsense_scan();
133
134 // Capsense Sense Functions
135 void testColumn  ( uint8_t strobe );
136 void sampleColumn( uint8_t column );
137
138 // Low-level Capsense Functions
139 void strobe_w( uint8_t strobe_num );
140 void recovery( uint8_t on );
141
142
143
144 // ----- Variables -----
145
146 // Buffer used to inform the macro processing module which keys have been detected as pressed
147 volatile uint8_t KeyIndex_Buffer[KEYBOARD_BUFFER];
148 volatile uint8_t KeyIndex_BufferUsed;
149
150
151 // Scan Module command dictionary
152 const char scanCLIDictName[] = "DPH Module Commands";
153 const CLIDictItem scanCLIDict[] = {
154         { "echo",        "Example command, echos the arguments.", cliFunc_echo },
155         { "avgDebug",    "Enables/Disables averaging results." NL "\t\tDisplays each average, starting from Key 0x00, ignoring 0 valued averages.", cliFunc_avgDebug },
156         { "keyDebug",    "Enables/Disables long debug for each keypress." NL "\t\tkeycode - [strobe:mux] : sense val : threshold+delta=total : margin", cliFunc_keyDebug },
157         { "pressDebug",  "Enables/Disables short debug for each keypress.", cliFunc_pressDebug },
158         { "problemKeys", "Display current list of problem keys,", cliFunc_problemKeys },
159         { "senseDebug",  "Prints out the current sense table N times." NL "\t\tsense:max sense:delta", cliFunc_senseDebug },
160         { 0, 0, 0 } // Null entry for dictionary end
161 };
162
163 // CLI Control Variables
164 uint8_t enableAvgDebug   = 0;
165 uint8_t enableKeyDebug   = 0;
166 uint8_t enablePressDebug = 1;
167 uint8_t senseDebugCount  = 3; // In order to get boot-time oddities
168
169
170 // Variables used to calculate the starting sense value (averaging)
171 uint32_t full_avg = 0;
172 uint32_t high_avg = 0;
173 uint32_t  low_avg = 0;
174
175 uint8_t  high_count = 0;
176 uint8_t   low_count = 0;
177
178
179 uint16_t samples[MAX_STROBES][MUXES_COUNT];   // Overall table of cap sense ADC values
180 uint16_t sampleMax[MAX_STROBES][MUXES_COUNT]; // Records the max seen ADC value
181
182 uint8_t  key_activity = 0; // Increments for each detected key per each full scan of the keyboard, it is reset before each full scan
183 uint16_t key_idle     = 0; // Defines how scans after all keys were released before starting averaging again
184 uint8_t  key_release  = 0; // Indicates if going from key press state to release state (some keys pressed to no keys pressed)
185
186 uint16_t threshold = THRESHOLD;
187
188 uint16_t keys_averages_acc[KEY_COUNT];
189 uint16_t keys_averages    [KEY_COUNT];
190 uint8_t  keys_debounce    [KEY_COUNT]; // Contains debounce statistics
191 uint8_t  keys_problem     [KEY_COUNT]; // Marks keys that should be ignored (determined by averaging at startup)
192
193 // TODO: change this to 'booting', then count down.
194 uint16_t boot_count = 0;
195
196 uint8_t total_strobes = MAX_STROBES;
197 uint8_t strobe_map[MAX_STROBES];
198
199
200
201 // ----- Functions -----
202
203 // Initial setup for cap sense controller
204 inline void Scan_setup()
205 {
206         // Register Scan CLI dictionary
207         CLI_registerDictionary( scanCLIDict, scanCLIDictName );
208
209         // Scan for active strobes
210         // NOTE1: On IBM PCBs, each strobe line that is *NOT* used is connected to GND.
211         //       This means, the strobe GPIO can be set to Tri-State pull-up to detect which strobe lines are not used.
212         // NOTE2: This will *NOT* detect floating strobes.
213         // NOTE3: Rev 0.4, the strobe numbers are reversed, so D0 is actually strobe 0 and C7 is strobe 17
214         info_msg("Detecting Strobes...");
215
216         DDRC  = 0;
217         PORTC = C_MASK;
218         DDRD  = 0;
219         PORTD = D_MASK;
220         DDRE  = 0;
221         PORTE = E_MASK;
222
223         // Initially there are 0 strobes
224         total_strobes = 0;
225
226         // Iterate over each the strobes
227         for ( uint8_t strobe = 0; strobe < MAX_STROBES; strobe++ )
228         {
229                 uint8_t detected = 0;
230
231                 // If PIN is high, then strobe is *NOT* connected to GND and may be a strobe
232                 switch ( strobe )
233                 {
234
235                 // Strobe Mappings
236                 //              Rev  Rev
237                 //              0.2  0.4
238 #ifndef REV0_4_DEBUG // XXX These pins should be reworked, and connect to GND on Rev 0.4
239                 case 0:  // D0   0   n/c
240                 case 1:  // D1   1   n/c
241 #endif
242                 case 2:  // D2   2   15
243                 case 3:  // D3   3   14
244                 case 4:  // D4   4   13
245                 case 5:  // D5   5   12
246                 case 6:  // D6   6   11
247                 case 7:  // D7   7   10
248                         detected = PIND & (1 << strobe);
249                         break;
250
251                 case 8:  // E0   8    9
252                 case 9:  // E1   9    8
253                         detected = PINE & (1 << (strobe - 8));
254                         break;
255
256                 case 10: // C0  10    7
257                 case 11: // C1  11    6
258                 case 12: // C2  12    5
259                 case 13: // C3  13    4
260                 case 14: // C4  14    3
261                 case 15: // C5  15    2
262 #ifndef REV0_2_DEBUG // XXX If not using the 18 pin connector on Rev 0.2, rework these pins to GND
263                 case 16: // C6  16    1
264                 case 17: // C7  17    0
265 #endif
266                         detected = PINC & (1 << (strobe - 10));
267                         break;
268
269                 default:
270                         break;
271                 }
272
273                 // Potential strobe line detected
274                 if ( detected )
275                 {
276                         strobe_map[total_strobes] = strobe;
277                         total_strobes++;
278                 }
279         }
280
281         printInt8( total_strobes );
282         print( " strobes found." NL );
283
284         // Setup Pins for Strobing
285         DDRC  = C_MASK;
286         PORTC = 0;
287         DDRD  = D_MASK;
288         PORTD = 0;
289         DDRE  = E_MASK;
290         PORTE = 0 ;
291
292         // Initialize ADC
293         setup_ADC();
294
295         // Reset debounce table
296         for ( int i = 0; i < KEY_COUNT; ++i )
297         {
298                 keys_debounce[i] = 0;
299         }
300
301         // Warm things up a bit before we start collecting data, taking real samples.
302         for ( uint8_t i = 0; i < total_strobes; ++i )
303         {
304                 sampleColumn( strobe_map[i] );
305         }
306 }
307
308
309 // Main Detection Loop
310 // This is where the important stuff happens
311 inline uint8_t Scan_loop()
312 {
313         capsense_scan();
314
315         // Return non-zero if macro and USB processing should be delayed
316         // Macro processing will always run if returning 0
317         // USB processing only happens once the USB send timer expires, if it has not, Scan_loop will be called
318         //  after the macro processing has been completed
319         return 0;
320 }
321
322
323 // Signal KeyIndex_Buffer that it has been properly read
324 // NOTE: Only really required for implementing "tricks" in converters for odd protocols
325 void Scan_finishedWithMacro( uint8_t sentKeys )
326 {
327         return;
328 }
329
330
331 // Signal KeyIndex_Buffer that it has been properly read and sent out by the USB module
332 // NOTE: Only really required for implementing "tricks" in converters for odd protocols
333 void Scan_finishedWithOutput( uint8_t sentKeys )
334 {
335         return;
336 }
337
338
339 inline void capsense_scan()
340 {
341         // Accumulated average used for the next scan
342         uint32_t cur_full_avg = 0;
343         uint32_t cur_high_avg = 0;
344
345         // Reset average counters
346         low_avg = 0;
347         low_count = 0;
348
349         high_count = 0;
350
351         // Reset key activity, if there is no key activity, averages will accumulate for sense deltas, otherwise they will be reset
352         key_activity = 0;
353
354         // Scan each of the mapped strobes in the matrix
355         for ( uint8_t strober = 0; strober < total_strobes; ++strober )
356         {
357                 uint8_t map_strobe = strobe_map[strober];
358
359                 // Sample the ADCs for the given column/strobe
360                 sampleColumn( map_strobe );
361
362                 // Only process sense data if warmup is finished
363                 if ( boot_count >= WARMUP_LOOPS )
364                 {
365                         testColumn( map_strobe );
366                 }
367
368                 uint8_t strobe_line = map_strobe << MUXES_COUNT_XSHIFT;
369                 for ( int mux = 0; mux < MUXES_COUNT; ++mux )
370                 {
371                         // discard sketchy low bit, and meaningless high bits.
372                         uint8_t sample = samples[map_strobe][mux] >> 1;
373                         keys_averages_acc[strobe_line + mux] += sample;
374                 }
375
376                 // Accumulate 3 total averages (used for determining starting average during warmup)
377                 //     full_avg - Average of all sampled lines on the previous scan set
378                 // cur_full_avg - Average of all sampled lines for this scan set
379                 //     high_avg - Average of all sampled lines above full_avg on the previous scan set
380                 // cur_high_avg - Average of all sampled lines above full_avg
381                 //      low_avg - Average of all sampled lines below or equal to full_avg
382                 if ( boot_count < WARMUP_LOOPS )
383                 {
384                         for ( uint8_t mux = 0; mux < MUXES_COUNT; ++mux )
385                         {
386                                 uint8_t sample = samples[map_strobe][mux] >> 1;
387
388                                 // Sample is high, add it to high avg
389                                 if ( sample > full_avg )
390                                 {
391                                         high_count++;
392                                         cur_high_avg += sample;
393                                 }
394                                 // Sample is low, add it to low avg
395                                 else
396                                 {
397                                         low_count++;
398                                         low_avg += sample;
399                                 }
400
401                                 // If sample is higher than previous high_avg, then mark as "problem key"
402                                 // XXX Giving a bit more margin to pass (high_avg vs. high_avg + high_avg - full_avg) -HaaTa
403                                 keys_problem[strobe_line + mux] = sample > high_avg + (high_avg - full_avg) ? sample : 0;
404
405                                 // Prepare for next average
406                                 cur_full_avg += sample;
407                         }
408                 }
409         } // for strober
410
411         // Update total sense average (only during warm-up)
412         if ( boot_count < WARMUP_LOOPS )
413         {
414                 full_avg = cur_full_avg / (total_strobes * MUXES_COUNT);
415                 high_avg = cur_high_avg / high_count;
416                 low_avg /= low_count;
417
418                 // Update the base average value using the low_avg (best chance of not ignoring a keypress)
419                 for ( int i = 0; i < KEY_COUNT; ++i )
420                 {
421                         keys_averages[i] = low_avg;
422                         keys_averages_acc[i] = low_avg;
423                 }
424         }
425
426         // Warm up voltage references
427         if ( boot_count < WARMUP_LOOPS )
428         {
429                 boot_count++;
430
431                 switch ( boot_count )
432                 {
433                 // First loop
434                 case 1:
435                         // Show msg at first iteration only
436                         info_msg("Warming up the voltage references");
437                         break;
438                 // Middle iterations
439                 case 300:
440                 case 600:
441                 case 900:
442                 case 1200:
443                         print(".");
444                         break;
445                 // Last loop
446                 case WARMUP_STOP:
447                         print( NL );
448                         info_msg("Warmup finished using ");
449                         printInt16( WARMUP_LOOPS );
450                         print(" iterations" NL );
451
452                         // Display the final calculated averages of all the sensed strobes
453                         info_msg("Full average (");
454                         printInt8( total_strobes * MUXES_COUNT );
455                         print("): ");
456                         printHex( full_avg );
457
458                         print("  High average (");
459                         printInt8( high_count );
460                         print("): ");
461                         printHex( high_avg );
462
463                         print("  Low average (");
464                         printInt8( low_count );
465                         print("): ");
466                         printHex( low_avg );
467
468                         print("  Rejection threshold: ");
469                         printHex( high_avg + (high_avg - full_avg) );
470                         print( NL );
471
472                         // Display problem keys, and the sense value at the time
473                         for ( uint8_t key = 0; key < KEY_COUNT; key++ )
474                         {
475                                 if ( keys_problem[key] )
476                                 {
477                                         warn_msg("Problem key detected: ");
478                                         printHex( key );
479                                         print(" (");
480                                         printHex( keys_problem[key] );
481                                         print(")" NL );
482                                 }
483                         }
484
485                         info_print("If problem keys were detected, and were being held down, they will be reset as soon as let go.");
486                         info_print("Some keys have unusually high sense values, on the first press they should be re-enabled.");
487                         break;
488                 }
489         }
490         else
491         {
492                 // No keypress, accumulate averages
493                 if( !key_activity )
494                 {
495                         // Only start averaging once the idle counter has counted down to 0
496                         if ( key_idle == 0 )
497                         {
498                                 // Average Debugging
499                                 if ( enableAvgDebug )
500                                 {
501                                         print("\033[1mAvg\033[0m: ");
502                                 }
503
504                                 // aggregate
505                                 for ( uint8_t i = 0; i < KEY_COUNT; ++i )
506                                 {
507                                         uint16_t acc = keys_averages_acc[i];
508                                         //uint16_t acc = keys_averages_acc[i] >> IDLE_COUNT_SHIFT; // XXX This fixes things... -HaaTa
509                                         uint32_t av = keys_averages[i];
510
511                                         av = (av << KEYS_AVERAGES_MIX_SHIFT) - av + acc;
512                                         av >>= KEYS_AVERAGES_MIX_SHIFT;
513
514                                         keys_averages[i] = av;
515                                         keys_averages_acc[i] = 0;
516
517                                         // Average Debugging
518                                         if ( enableAvgDebug && av > 0 )
519                                         {
520                                                 printHex( av );
521                                                 print(" ");
522                                         }
523                                 }
524
525                                 // Average Debugging
526                                 if ( enableAvgDebug )
527                                 {
528                                         print( NL );
529                                 }
530
531                                 // No key presses detected, set key_release indicator
532                                 key_release = 1;
533                         }
534                         // Otherwise decrement the idle counter
535                         else
536                         {
537                                 key_idle--;
538                         }
539                 }
540                 // Keypresses, reset accumulators
541                 else if ( key_release )
542                 {
543                         for ( uint8_t c = 0; c < KEY_COUNT; ++c ) { keys_averages_acc[c] = 0; }
544
545                         key_release = 0;
546                 }
547
548                 // If the debugging sense table is non-zero, display
549                 if ( senseDebugCount > 0 )
550                 {
551                         senseDebugCount--;
552                         print( NL );
553                         dumpSenseTable();
554                 }
555         }
556 }
557
558
559 void setup_ADC()
560 {
561         // disable adc digital pins.
562         DIDR1 |= (1 << AIN0D) | (1<<AIN1D); // set disable on pins 1,0.
563         DDRF = 0x0;
564         PORTF = 0x0;
565         uint8_t mux = 0 & 0x1f; // 0 == first. // 0x1e = 1.1V ref.
566
567         // 0 = external aref 1,1 = 2.56V internal ref
568         uint8_t aref = ((1 << REFS1) | (1 << REFS0)) & ((1 << REFS1) | (1 << REFS0));
569         uint8_t adate = (1 << ADATE) & (1 << ADATE); // trigger enable
570         uint8_t trig = 0 & ((1 << ADTS0) | (1 << ADTS1) | (1 << ADTS2)); // 0 = free running
571         // ps2, ps1 := /64 ( 2^6 ) ps2 := /16 (2^4), ps1 := 4, ps0 :=2, PS1,PS0 := 8 (2^8)
572         uint8_t prescale = ( ((PRESCALE) << PRESCALE_SHIFT) & PRESCALE_MASK ); // 001 == 2^1 == 2
573         uint8_t hispeed = (1 << ADHSM);
574         uint8_t en_mux = (1 << ACME);
575
576         ADCSRA = (1 << ADEN) | prescale; // ADC enable
577
578         // select ref.
579         //ADMUX |= ((1 << REFS1) | (1 << REFS0)); // 2.56 V internal.
580         //ADMUX |= ((1 << REFS0) ); // Vcc with external cap.
581         //ADMUX &= ~((1 << REFS1) | (1 << REFS0)); // 0,0 : aref.
582         ADMUX = aref | mux | ADLAR_BITS;
583
584         // set free-running
585         ADCSRA |= adate; // trigger enable
586         ADCSRB  = en_mux | hispeed | trig | (ADCSRB & ~((1 << ADTS0) | (1 << ADTS1) | (1 << ADTS2))); // trigger select free running
587
588         ADCSRA |= (1 << ADEN); // ADC enable
589         ADCSRA |= (1 << ADSC); // start conversions q
590 }
591
592
593 void recovery( uint8_t on )
594 {
595         DDRB  |=  (1 << RECOVERY_CONTROL);
596         PORTB &= ~(1 << RECOVERY_SINK);   // SINK always zero
597         DDRB  &= ~(1 << RECOVERY_SOURCE); // SOURCE high imp
598
599         if ( on )
600         {
601                 // set strobes to sink to gnd.
602                 DDRC |= C_MASK;
603                 DDRD |= D_MASK;
604                 DDRE |= E_MASK;
605
606                 PORTC &= ~C_MASK;
607                 PORTD &= ~D_MASK;
608                 PORTE &= ~E_MASK;
609
610                 DDRB  |= (1 << RECOVERY_SINK);   // SINK pull
611                 PORTB |= (1 << RECOVERY_CONTROL);
612                 PORTB |= (1 << RECOVERY_SOURCE); // SOURCE high
613                 DDRB  |= (1 << RECOVERY_SOURCE);
614         }
615         else
616         {
617                 PORTB &= ~(1 << RECOVERY_CONTROL);
618                 DDRB  &= ~(1 << RECOVERY_SOURCE);
619                 PORTB &= ~(1 << RECOVERY_SOURCE); // SOURCE low
620                 DDRB  &= ~(1 << RECOVERY_SINK);   // SINK high-imp
621         }
622 }
623
624
625 void hold_sample( uint8_t on )
626 {
627         if ( !on )
628         {
629                 PORTB |= (1 << SAMPLE_CONTROL);
630                 DDRB  |= (1 << SAMPLE_CONTROL);
631         }
632         else
633         {
634                 DDRB  |=  (1 << SAMPLE_CONTROL);
635                 PORTB &= ~(1 << SAMPLE_CONTROL);
636         }
637 }
638
639
640 void strobe_w( uint8_t strobe_num )
641 {
642         PORTC &= ~(C_MASK);
643         PORTD &= ~(D_MASK);
644         PORTE &= ~(E_MASK);
645
646         // Strobe table
647         // Not all strobes are used depending on which are detected
648         switch ( strobe_num )
649         {
650
651         case 0:  PORTD |= (1 << 0); break;
652         case 1:  PORTD |= (1 << 1); break;
653         case 2:  PORTD |= (1 << 2); break;
654         case 3:  PORTD |= (1 << 3); break;
655         case 4:  PORTD |= (1 << 4); break;
656         case 5:  PORTD |= (1 << 5); break;
657         case 6:  PORTD |= (1 << 6); break;
658         case 7:  PORTD |= (1 << 7); break;
659
660         case 8:  PORTE |= (1 << 0); break;
661         case 9:  PORTE |= (1 << 1); break;
662
663         case 10: PORTC |= (1 << 0); break;
664         case 11: PORTC |= (1 << 1); break;
665         case 12: PORTC |= (1 << 2); break;
666         case 13: PORTC |= (1 << 3); break;
667         case 14: PORTC |= (1 << 4); break;
668         case 15: PORTC |= (1 << 5); break;
669         case 16: PORTC |= (1 << 6); break;
670         case 17: PORTC |= (1 << 7); break;
671
672         default:
673                 break;
674         }
675 }
676
677
678 inline uint16_t getADC(void)
679 {
680         ADCSRA |= (1 << ADIF); // clear int flag by writing 1.
681
682         //wait for last read to complete.
683         while ( !( ADCSRA & (1 << ADIF) ) );
684
685         return ADC; // return sample
686 }
687
688
689 void sampleColumn( uint8_t column )
690 {
691         // ensure all probe lines are driven low, and chill for recovery delay.
692         ADCSRA |= (1 << ADEN) | (1 << ADSC); // enable and start conversions
693
694         PORTC &= ~C_MASK;
695         PORTD &= ~D_MASK;
696         PORTE &= ~E_MASK;
697
698         PORTF = 0;
699         DDRF  = 0;
700
701         recovery( OFF );
702         strobe_w( column );
703
704         hold_sample( OFF );
705         SET_FULL_MUX( 0 );
706
707         // Allow strobes to settle
708         for ( uint8_t i = 0; i < STROBE_SETTLE; ++i ) { getADC(); }
709
710         hold_sample( ON );
711
712         uint8_t mux = 0;
713         SET_FULL_MUX( mux );
714         getADC(); // throw away; unknown mux.
715         do {
716                 SET_FULL_MUX( mux + 1 ); // our *next* sample will use this
717
718                 // retrieve current read.
719                 uint16_t readVal = getADC();
720                 samples[column][mux] = readVal;
721
722                 // Update max sense sample table
723                 if ( readVal > sampleMax[column][mux] )
724                 {
725                         sampleMax[column][mux] = readVal;
726                 }
727
728                 mux++;
729
730         } while ( mux < 8 );
731
732         hold_sample( OFF );
733         recovery( ON );
734
735         // turn off adc.
736         ADCSRA &= ~(1 << ADEN);
737
738         // pull all columns' strobe-lines low.
739         DDRC |= C_MASK;
740         DDRD |= D_MASK;
741         DDRE |= E_MASK;
742
743         PORTC &= ~C_MASK;
744         PORTD &= ~D_MASK;
745         PORTE &= ~E_MASK;
746 }
747
748
749 void testColumn( uint8_t strobe )
750 {
751         uint16_t db_delta = 0;
752         uint8_t  db_sample = 0;
753         uint16_t db_threshold = 0;
754
755         uint8_t column = 0;
756         uint8_t bit = 1;
757
758         for ( uint8_t mux = 0; mux < MUXES_COUNT; ++mux )
759         {
760                 uint16_t delta = keys_averages[(strobe << MUXES_COUNT_XSHIFT) + mux];
761
762                 uint8_t key = (strobe << MUXES_COUNT_XSHIFT) + mux;
763
764                 // Check if this is a bad key (e.g. test point, or non-existent key)
765                 if ( keys_problem[key] )
766                 {
767                         // If the sample value of the problem key goes above initally recorded result + threshold
768                         //  re-enable the key
769                         if ( (db_sample = samples[strobe][mux] >> 1) > keys_problem[key] + threshold )
770                         //if ( (db_sample = samples[strobe][mux] >> 1) < high_avg )
771                         {
772                                 info_msg("Re-enabling problem key: ");
773                                 printHex( key );
774                                 print( NL );
775
776                                 keys_problem[key] = 0;
777                         }
778
779                         // Do not waste any more cycles processing, regardless, a keypress cannot be detected
780                         continue;
781                 }
782
783                 // Keypress detected
784                 //  db_sample (uint8_t), discard meaningless high bit, and garbage low bit
785                 if ( (db_sample = samples[strobe][mux] >> 1) > (db_threshold = threshold) + (db_delta = delta) )
786                 {
787                         column |= bit;
788                         key_activity++; // No longer idle, stop averaging ADC data
789                         key_idle = KEY_IDLE_SCANS; // Reset idle count-down
790
791                         // Only register keypresses once the warmup is complete, or not enough debounce info
792                         if ( keys_debounce[key] <= DEBOUNCE_THRESHOLD )
793                         {
794                                 // Add to the Macro processing buffer if debounce criteria met
795                                 // Automatically handles converting to a USB code and sending off to the PC
796                                 if ( keys_debounce[key] == DEBOUNCE_THRESHOLD )
797                                 {
798                                         // Debug message, pressDebug CLI
799                                         if ( enablePressDebug )
800                                         {
801                                                 print("0x");
802                                                 printHex_op( key, 2 );
803                                                 print(" ");
804                                         }
805
806                                         // Initial Keypress
807                                         Macro_keyState( key, 0x01 );
808                                 }
809                                 else if ( keys_debounce[key] >= DEBOUNCE_THRESHOLD )
810                                 {
811                                         // Held Key
812                                         Macro_keyState( key, 0x02 );
813                                 }
814
815                                 keys_debounce[key]++;
816
817                         }
818
819                         // Long form key debugging
820                         if ( enableKeyDebug )
821                         {
822                                 // Debug message
823                                 // <key> [<strobe>:<mux>] : <sense val> : <delta + threshold> : <margin>
824                                 dbug_msg("0x");
825                                 printHex_op( key, 1 );
826                                 print(" [");
827                                 printInt8( strobe );
828                                 print(":");
829                                 printInt8( mux );
830                                 print("] : ");
831                                 printHex( db_sample ); // Sense
832                                 print(" : ");
833                                 printHex( db_threshold );
834                                 print("+");
835                                 printHex( db_delta );
836                                 print("=");
837                                 printHex( db_threshold + db_delta ); // Sense compare
838                                 print(" : ");
839                                 printHex( db_sample - ( db_threshold + db_delta ) ); // Margin
840                                 print( NL );
841                         }
842                 }
843                 // Clear debounce entry if no keypress detected
844                 else
845                 {
846                         // Release Key
847                         if ( KeyIndex_BufferUsed > 0 && keys_debounce[key] >= DEBOUNCE_THRESHOLD )
848                         {
849                                 Macro_keyState( key, 0x03 );
850                         }
851
852                         // Clear debounce entry
853                         keys_debounce[key] = 0;
854                 }
855
856                 bit <<= 1;
857         }
858 }
859
860
861 void dumpSenseTable()
862 {
863         // Initial table alignment, with base threshold used for every key
864         print("\033[1m");
865         printHex( threshold );
866         print("\033[0m       ");
867
868         // Print out headers first
869         for ( uint8_t mux = 0; mux < MUXES_COUNT; ++mux )
870         {
871                 print("  Mux \033[1m");
872                 printInt8( mux );
873                 print("\033[0m  ");
874         }
875
876         print( NL );
877
878         // Display the full strobe/sense table
879         for ( uint8_t strober = 0; strober < total_strobes; ++strober )
880         {
881                 uint8_t strobe = strobe_map[strober];
882
883                 // Display the strobe
884                 print("Strobe \033[1m");
885                 printHex( strobe );
886                 print("\033[0m ");
887
888                 // For each mux, display sense:threshold:delta
889                 for ( uint8_t mux = 0; mux < MUXES_COUNT; ++mux )
890                 {
891                         uint8_t delta = keys_averages[(strobe << MUXES_COUNT_XSHIFT) + mux];
892                         uint8_t sample = samples[strobe][mux] >> 1;
893                         uint8_t max = sampleMax[strobe][mux] >> 1;
894
895                         // Indicate if the key is being pressed by displaying green
896                         if ( sample > delta + threshold )
897                         {
898                                 print("\033[1;32m");
899                         }
900
901                         printHex_op( sample, 2 );
902                         print(":");
903                         printHex_op( max, 2 );
904                         print(":");
905                         printHex_op( delta, 2 );
906                         print("\033[0m ");
907                 }
908
909                 // New line for each strobe
910                 print( NL );
911         }
912 }
913
914
915 // ----- CLI Command Functions -----
916
917 // XXX Just an example command showing how to parse arguments (more complex than generally needed)
918 void cliFunc_echo( char* args )
919 {
920         char* curArgs;
921         char* arg1Ptr;
922         char* arg2Ptr = args;
923
924         // Parse args until a \0 is found
925         while ( 1 )
926         {
927                 print( NL ); // No \r\n by default after the command is entered
928
929                 curArgs = arg2Ptr; // Use the previous 2nd arg pointer to separate the next arg from the list
930                 CLI_argumentIsolation( curArgs, &arg1Ptr, &arg2Ptr );
931
932                 // Stop processing args if no more are found
933                 if ( *arg1Ptr == '\0' )
934                         break;
935
936                 // Print out the arg
937                 dPrint( arg1Ptr );
938         }
939 }
940
941 void cliFunc_avgDebug( char* args )
942 {
943         print( NL );
944
945         // Args ignored, just toggling
946         if ( enableAvgDebug )
947         {
948                 info_print("Cap Sense averaging debug disabled.");
949                 enableAvgDebug = 0;
950         }
951         else
952         {
953                 info_print("Cap Sense averaging debug enabled.");
954                 enableAvgDebug = 1;
955         }
956 }
957
958 void cliFunc_keyDebug( char* args )
959 {
960         print( NL );
961
962         // Args ignored, just toggling
963         if ( enableKeyDebug )
964         {
965                 info_print("Cap Sense key long debug disabled - pre debounce.");
966                 enableKeyDebug = 0;
967         }
968         else
969         {
970                 info_print("Cap Sense key long debug enabled - pre debounce.");
971                 enableKeyDebug = 1;
972         }
973 }
974
975 void cliFunc_pressDebug( char* args )
976 {
977         print( NL );
978
979         // Args ignored, just toggling
980         if ( enablePressDebug )
981         {
982                 info_print("Cap Sense key debug disabled - post debounce.");
983                 enablePressDebug = 0;
984         }
985         else
986         {
987                 info_print("Cap Sense key debug enabled - post debounce.");
988                 enablePressDebug = 1;
989         }
990 }
991
992 void cliFunc_problemKeys( char* args )
993 {
994         print( NL );
995
996         uint8_t count = 0;
997
998         // Args ignored, just displaying
999         // Display problem keys, and the sense value at the time
1000         for ( uint8_t key = 0; key < KEY_COUNT; key++ )
1001         {
1002                 if ( keys_problem[key] )
1003                 {
1004                         if ( count++ == 0 )
1005                         {
1006                                 warn_msg("Problem keys: ");
1007                         }
1008                         printHex( key );
1009                         print(" (");
1010                         printHex( keys_problem[key] );
1011                         print(")   "  );
1012                 }
1013         }
1014 }
1015
1016 void cliFunc_senseDebug( char* args )
1017 {
1018         // Parse code from argument
1019         //  NOTE: Only first argument is used
1020         char* arg1Ptr;
1021         char* arg2Ptr;
1022         CLI_argumentIsolation( args, &arg1Ptr, &arg2Ptr );
1023
1024         // Default to a single print
1025         senseDebugCount = 1;
1026
1027         // If there was an argument, use that instead
1028         if ( *arg1Ptr != '\0' )
1029         {
1030                 senseDebugCount = numToInt( arg1Ptr );
1031         }
1032 }
1033