]> git.donarmstrong.com Git - kiibohd-controller.git/blob - Scan/DPH/scan_loop.c
27eb92ee32fd0aa9b21c5dbeec2800c44a8b89a8
[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 <print.h>
27
28 // Local Includes
29 #include "scan_loop.h"
30
31
32
33 // ----- Defines -----
34
35 // TODO dfj defines...needs commenting and maybe some cleaning...
36 #define MAX_PRESS_DELTA_MV 450 // As measured from the Teensy ADC pin
37 #define THRESHOLD_MV (MAX_PRESS_DELTA_MV >> 1)
38 //(2560 / (0x3ff/2)) ~= 5
39 #define MV_PER_ADC 5
40 #define THRESHOLD (THRESHOLD_MV / MV_PER_ADC)
41
42 #define STROBE_SETTLE 1
43
44 #define ADHSM 7
45
46 // Right justification of ADLAR
47 #define ADLAR_BITS 0
48
49 // full muxmask
50 #define FULL_MUX_MASK ((1 << MUX0) | (1 << MUX1) | (1 << MUX2) | (1 << MUX3) | (1 << MUX4))
51
52 // F0-f7 pins only muxmask.
53 #define MUX_MASK ((1 << MUX0) | (1 << MUX1) | (1 << MUX2))
54
55 // Strobe Masks
56 #define D_MASK (0xff)
57 #define E_MASK (0x03)
58 #define C_MASK (0xff)
59
60 // set ADC clock prescale
61 #define PRESCALE_MASK ((1 << ADPS0) | (1 << ADPS1) | (1 << ADPS2))
62 #define PRESCALE_SHIFT (ADPS0)
63 #define PRESCALE 3
64
65 // Max number of strobes supported by the hardware
66 // Strobe lines are detected at startup, extra strobes cause anomalies like phantom keypresses
67 #define MAX_STROBES 18
68
69 // Number of consecutive samples required to pass debounce
70 #define DEBOUNCE_THRESHOLD 5
71
72 // Scans to remain idle after all keys were release before starting averaging
73 // XXX So this makes the initial keypresses fast,
74 //      but it's still possible to lose a keypress if you press at the wrong time -HaaTa
75 #define KEY_IDLE_SCANS 30000
76
77 // Total number of muxes/sense lines available
78 #define MUXES_COUNT 8
79 #define MUXES_COUNT_XSHIFT 3
80
81 // Number of warm-up loops before starting to scan keys
82 #define WARMUP_LOOPS ( 1024 )
83 #define WARMUP_STOP (WARMUP_LOOPS - 1)
84
85 #define SAMPLE_CONTROL 3
86
87 #define KEY_COUNT ((MAX_STROBES) * (MUXES_COUNT))
88
89 #define RECOVERY_CONTROL 1
90 #define RECOVERY_SOURCE  0
91 #define RECOVERY_SINK    2
92
93 #define ON  1
94 #define OFF 0
95
96 // mix in 1/4 of the current average to the running average. -> (@mux_mix = 2)
97 #define MUX_MIX 2
98
99 #define IDLE_COUNT_SHIFT 8
100
101 // av = (av << shift) - av + sample; av >>= shift
102 // e.g. 1 -> (av + sample) / 2 simple average of new and old
103 //      2 -> (3 * av + sample) / 4 i.e. 3:1 mix of old to new.
104 //      3 -> (7 * av + sample) / 8 i.e. 7:1 mix of old to new.
105 #define KEYS_AVERAGES_MIX_SHIFT 3
106
107
108
109 // ----- Macros -----
110
111 // Select mux
112 #define SET_FULL_MUX(X) ((ADMUX) = (((ADMUX) & ~(FULL_MUX_MASK)) | ((X) & (FULL_MUX_MASK))))
113
114
115
116 // ----- Function Declarations -----
117
118 // CLI Functions
119 void cliFunc_avgDebug   ( char* args );
120 void cliFunc_echo       ( char* args );
121 void cliFunc_keyDebug   ( char* args );
122 void cliFunc_pressDebug ( char* args );
123 void cliFunc_problemKeys( char* args );
124 void cliFunc_senseDebug ( char* args );
125
126 // Debug Functions
127 void dumpSenseTable();
128
129 // High-level Capsense Functions
130 void setup_ADC();
131 void capsense_scan();
132
133 // Capsense Sense Functions
134 void testColumn  ( uint8_t strobe );
135 void sampleColumn( uint8_t column );
136
137 // Low-level Capsense Functions
138 void strobe_w( uint8_t strobe_num );
139 void recovery( uint8_t on );
140
141
142
143 // ----- Variables -----
144
145 // Buffer used to inform the macro processing module which keys have been detected as pressed
146 volatile uint8_t KeyIndex_Buffer[KEYBOARD_BUFFER];
147 volatile uint8_t KeyIndex_BufferUsed;
148
149
150 // Scan Module command dictionary
151 char*       scanCLIDictName = "DPH Module Commands";
152 CLIDictItem scanCLIDict[] = {
153         { "echo",        "Example command, echos the arguments.", cliFunc_echo },
154         { "avgDebug",    "Enables/Disables averaging results." NL "\t\tDisplays each average, starting from Key 0x00, ignoring 0 valued averages.", cliFunc_avgDebug },
155         { "keyDebug",    "Enables/Disables long debug for each keypress." NL "\t\tkeycode - [strobe:mux] : sense val : threshold+delta=total : margin", cliFunc_keyDebug },
156         { "pressDebug",  "Enables/Disables short debug for each keypress.", cliFunc_pressDebug },
157         { "problemKeys", "Display current list of problem keys,", cliFunc_problemKeys },
158         { "senseDebug",  "Prints out the current sense table N times." NL "\t\tsense:max sense:delta", cliFunc_senseDebug },
159         { 0, 0, 0 } // Null entry for dictionary end
160 };
161
162 // CLI Control Variables
163 uint8_t enableAvgDebug   = 0;
164 uint8_t enableKeyDebug   = 0;
165 uint8_t enablePressDebug = 1;
166 uint8_t senseDebugCount  = 3; // In order to get boot-time oddities
167
168
169 // Variables used to calculate the starting sense value (averaging)
170 uint32_t full_avg = 0;
171 uint32_t high_avg = 0;
172 uint32_t  low_avg = 0;
173
174 uint8_t  high_count = 0;
175 uint8_t   low_count = 0;
176
177
178 uint16_t samples[MAX_STROBES][MUXES_COUNT];   // Overall table of cap sense ADC values
179 uint16_t sampleMax[MAX_STROBES][MUXES_COUNT]; // Records the max seen ADC value
180
181 uint8_t  key_activity = 0; // Increments for each detected key per each full scan of the keyboard, it is reset before each full scan
182 uint16_t key_idle     = 0; // Defines how scans after all keys were released before starting averaging again
183 uint8_t  key_release  = 0; // Indicates if going from key press state to release state (some keys pressed to no keys pressed)
184
185 uint16_t threshold = THRESHOLD;
186
187 uint16_t keys_averages_acc[KEY_COUNT];
188 uint16_t keys_averages    [KEY_COUNT];
189 uint8_t  keys_debounce    [KEY_COUNT]; // Contains debounce statistics
190 uint8_t  keys_problem     [KEY_COUNT]; // Marks keys that should be ignored (determined by averaging at startup)
191
192 // TODO: change this to 'booting', then count down.
193 uint16_t boot_count = 0;
194
195 uint8_t total_strobes = MAX_STROBES;
196 uint8_t strobe_map[MAX_STROBES];
197
198
199
200 // ----- Functions -----
201
202 // Initial setup for cap sense controller
203 inline void Scan_setup()
204 {
205         // Register Scan CLI dictionary
206         CLI_registerDictionary( scanCLIDict, scanCLIDictName );
207
208         // Scan for active strobes
209         // NOTE1: On IBM PCBs, each strobe line that is *NOT* used is connected to GND.
210         //       This means, the strobe GPIO can be set to Tri-State pull-up to detect which strobe lines are not used.
211         // NOTE2: This will *NOT* detect floating strobes.
212         // NOTE3: Rev 0.4, the strobe numbers are reversed, so D0 is actually strobe 0 and C7 is strobe 17
213         info_msg("Detecting Strobes...");
214
215         DDRC  = 0;
216         PORTC = C_MASK;
217         DDRD  = 0;
218         PORTD = D_MASK;
219         DDRE  = 0;
220         PORTE = E_MASK;
221
222         // Initially there are 0 strobes
223         total_strobes = 0;
224
225         // Iterate over each the strobes
226         for ( uint8_t strobe = 0; strobe < MAX_STROBES; strobe++ )
227         {
228                 uint8_t detected = 0;
229
230                 // If PIN is high, then strobe is *NOT* connected to GND and may be a strobe
231                 switch ( strobe )
232                 {
233
234                 // Strobe Mappings
235                 //              Rev  Rev
236                 //              0.2  0.4
237 #ifndef REV0_4_DEBUG // XXX These pins should be reworked, and connect to GND on Rev 0.4
238                 case 0:  // D0   0   n/c
239                 case 1:  // D1   1   n/c
240 #endif
241                 case 2:  // D2   2   15
242                 case 3:  // D3   3   14
243                 case 4:  // D4   4   13
244                 case 5:  // D5   5   12
245                 case 6:  // D6   6   11
246                 case 7:  // D7   7   10
247                         detected = PIND & (1 << strobe);
248                         break;
249
250                 case 8:  // E0   8    9
251                 case 9:  // E1   9    8
252                         detected = PINE & (1 << (strobe - 8));
253                         break;
254
255                 case 10: // C0  10    7
256                 case 11: // C1  11    6
257                 case 12: // C2  12    5
258                 case 13: // C3  13    4
259                 case 14: // C4  14    3
260                 case 15: // C5  15    2
261 #ifndef REV0_2_DEBUG // XXX If not using the 18 pin connector on Rev 0.2, rework these pins to GND
262                 case 16: // C6  16    1
263                 case 17: // C7  17    0
264 #endif
265                         detected = PINC & (1 << (strobe - 10));
266                         break;
267
268                 default:
269                         break;
270                 }
271
272                 // Potential strobe line detected
273                 if ( detected )
274                 {
275                         strobe_map[total_strobes] = strobe;
276                         total_strobes++;
277                 }
278         }
279
280         printInt8( total_strobes );
281         print( " strobes found." NL );
282
283         // Setup Pins for Strobing
284         DDRC  = C_MASK;
285         PORTC = 0;
286         DDRD  = D_MASK;
287         PORTD = 0;
288         DDRE  = E_MASK;
289         PORTE = 0 ;
290
291         // Initialize ADC
292         setup_ADC();
293
294         // Reset debounce table
295         for ( int i = 0; i < KEY_COUNT; ++i )
296         {
297                 keys_debounce[i] = 0;
298         }
299
300         // Warm things up a bit before we start collecting data, taking real samples.
301         for ( uint8_t i = 0; i < total_strobes; ++i )
302         {
303                 sampleColumn( strobe_map[i] );
304         }
305 }
306
307
308 // Main Detection Loop
309 // This is where the important stuff happens
310 inline uint8_t Scan_loop()
311 {
312         capsense_scan();
313
314         // Return non-zero if macro and USB processing should be delayed
315         // Macro processing will always run if returning 0
316         // USB processing only happens once the USB send timer expires, if it has not, Scan_loop will be called
317         //  after the macro processing has been completed
318         return 0;
319 }
320
321
322 // Signal KeyIndex_Buffer that it has been properly read
323 // NOTE: Only really required for implementing "tricks" in converters for odd protocols
324 void Scan_finishedWithBuffer( uint8_t sentKeys )
325 {
326         // Convenient place to clear the KeyIndex_Buffer
327         KeyIndex_BufferUsed = 0;
328         return;
329 }
330
331
332 // Signal KeyIndex_Buffer that it has been properly read and sent out by the USB module
333 // NOTE: Only really required for implementing "tricks" in converters for odd protocols
334 void Scan_finishedWithUSBBuffer( uint8_t sentKeys )
335 {
336         return;
337 }
338
339
340 inline void capsense_scan()
341 {
342         // Accumulated average used for the next scan
343         uint32_t cur_full_avg = 0;
344         uint32_t cur_high_avg = 0;
345
346         // Reset average counters
347         low_avg = 0;
348         low_count = 0;
349
350         high_count = 0;
351
352         // Reset key activity, if there is no key activity, averages will accumulate for sense deltas, otherwise they will be reset
353         key_activity = 0;
354
355         // Scan each of the mapped strobes in the matrix
356         for ( uint8_t strober = 0; strober < total_strobes; ++strober )
357         {
358                 uint8_t map_strobe = strobe_map[strober];
359
360                 // Sample the ADCs for the given column/strobe
361                 sampleColumn( map_strobe );
362
363                 // Only process sense data if warmup is finished
364                 if ( boot_count >= WARMUP_LOOPS )
365                 {
366                         testColumn( map_strobe );
367                 }
368
369                 uint8_t strobe_line = map_strobe << MUXES_COUNT_XSHIFT;
370                 for ( int mux = 0; mux < MUXES_COUNT; ++mux )
371                 {
372                         // discard sketchy low bit, and meaningless high bits.
373                         uint8_t sample = samples[map_strobe][mux] >> 1;
374                         keys_averages_acc[strobe_line + mux] += sample;
375                 }
376
377                 // Accumulate 3 total averages (used for determining starting average during warmup)
378                 //     full_avg - Average of all sampled lines on the previous scan set
379                 // cur_full_avg - Average of all sampled lines for this scan set
380                 //     high_avg - Average of all sampled lines above full_avg on the previous scan set
381                 // cur_high_avg - Average of all sampled lines above full_avg
382                 //      low_avg - Average of all sampled lines below or equal to full_avg
383                 if ( boot_count < WARMUP_LOOPS )
384                 {
385                         for ( uint8_t mux = 0; mux < MUXES_COUNT; ++mux )
386                         {
387                                 uint8_t sample = samples[map_strobe][mux] >> 1;
388
389                                 // Sample is high, add it to high avg
390                                 if ( sample > full_avg )
391                                 {
392                                         high_count++;
393                                         cur_high_avg += sample;
394                                 }
395                                 // Sample is low, add it to low avg
396                                 else
397                                 {
398                                         low_count++;
399                                         low_avg += sample;
400                                 }
401
402                                 // If sample is higher than previous high_avg, then mark as "problem key"
403                                 // XXX Giving a bit more margin to pass (high_avg vs. high_avg + high_avg - full_avg) -HaaTa
404                                 keys_problem[strobe_line + mux] = sample > high_avg + (high_avg - full_avg) ? sample : 0;
405
406                                 // Prepare for next average
407                                 cur_full_avg += sample;
408                         }
409                 }
410         } // for strober
411
412         // Update total sense average (only during warm-up)
413         if ( boot_count < WARMUP_LOOPS )
414         {
415                 full_avg = cur_full_avg / (total_strobes * MUXES_COUNT);
416                 high_avg = cur_high_avg / high_count;
417                 low_avg /= low_count;
418
419                 // Update the base average value using the low_avg (best chance of not ignoring a keypress)
420                 for ( int i = 0; i < KEY_COUNT; ++i )
421                 {
422                         keys_averages[i] = low_avg;
423                         keys_averages_acc[i] = low_avg;
424                 }
425         }
426
427         // Warm up voltage references
428         if ( boot_count < WARMUP_LOOPS )
429         {
430                 boot_count++;
431
432                 switch ( boot_count )
433                 {
434                 // First loop
435                 case 1:
436                         // Show msg at first iteration only
437                         info_msg("Warming up the voltage references");
438                         break;
439                 // Middle iterations
440                 case 300:
441                 case 600:
442                 case 900:
443                 case 1200:
444                         print(".");
445                         break;
446                 // Last loop
447                 case WARMUP_STOP:
448                         print( NL );
449                         info_msg("Warmup finished using ");
450                         printInt16( WARMUP_LOOPS );
451                         print(" iterations" NL );
452
453                         // Display the final calculated averages of all the sensed strobes
454                         info_msg("Full average (");
455                         printInt8( total_strobes * MUXES_COUNT );
456                         print("): ");
457                         printHex( full_avg );
458
459                         print("  High average (");
460                         printInt8( high_count );
461                         print("): ");
462                         printHex( high_avg );
463
464                         print("  Low average (");
465                         printInt8( low_count );
466                         print("): ");
467                         printHex( low_avg );
468
469                         print("  Rejection threshold: ");
470                         printHex( high_avg + (high_avg - full_avg) );
471                         print( NL );
472
473                         // Display problem keys, and the sense value at the time
474                         for ( uint8_t key = 0; key < KEY_COUNT; key++ )
475                         {
476                                 if ( keys_problem[key] )
477                                 {
478                                         warn_msg("Problem key detected: ");
479                                         printHex( key );
480                                         print(" (");
481                                         printHex( keys_problem[key] );
482                                         print(")" NL );
483                                 }
484                         }
485
486                         info_print("If problem keys were detected, and were being held down, they will be reset as soon as let go");
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 below full_avg (overall initial average)
768                         //  re-enable the key
769                         if ( (db_sample = samples[strobe][mux] >> 1) < full_avg )
770                         {
771                                 info_msg("Re-enabling problem key: ");
772                                 printHex( key );
773                                 print( NL );
774
775                                 keys_problem[key] = 0;
776                         }
777
778                         // Do not waste any more cycles processing, regardless, a keypress cannot be detected
779                         continue;
780                 }
781
782                 // Keypress detected
783                 //  db_sample (uint8_t), discard meaningless high bit, and garbage low bit
784                 if ( (db_sample = samples[strobe][mux] >> 1) > (db_threshold = threshold) + (db_delta = delta) )
785                 {
786                         column |= bit;
787                         key_activity++; // No longer idle, stop averaging ADC data
788                         key_idle = KEY_IDLE_SCANS; // Reset idle count-down
789
790                         // Only register keypresses once the warmup is complete, or not enough debounce info
791                         if ( keys_debounce[key] <= DEBOUNCE_THRESHOLD )
792                         {
793                                 // Add to the Macro processing buffer if debounce criteria met
794                                 // Automatically handles converting to a USB code and sending off to the PC
795                                 if ( keys_debounce[key] == DEBOUNCE_THRESHOLD )
796                                 {
797                                         // Debug message, pressDebug CLI
798                                         if ( enablePressDebug )
799                                         {
800                                                 print("0x");
801                                                 printHex_op( key, 2 );
802                                                 print(" ");
803                                         }
804
805                                         // Only add the key to the buffer once
806                                         // NOTE: Buffer can easily handle multiple adds, just more efficient
807                                         //        and nicer debug messages :P
808                                         //Macro_bufferAdd( key );
809                                 }
810
811                                 keys_debounce[key]++;
812
813                         }
814
815                         // Long form key debugging
816                         if ( enableKeyDebug )
817                         {
818                                 // Debug message
819                                 // <key> [<strobe>:<mux>] : <sense val> : <delta + threshold> : <margin>
820                                 dbug_msg("0x");
821                                 printHex_op( key, 2 );
822                                 print(" [");
823                                 printInt8( strobe );
824                                 print(":");
825                                 printInt8( mux );
826                                 print("] : ");
827                                 printHex( db_sample ); // Sense
828                                 print(" : ");
829                                 printHex( db_threshold );
830                                 print("+");
831                                 printHex( db_delta );
832                                 print("=");
833                                 printHex( db_threshold + db_delta ); // Sense compare
834                                 print(" : ");
835                                 printHex( db_sample - ( db_threshold + db_delta ) ); // Margin
836                                 print( NL );
837                         }
838                 }
839                 // Clear debounce entry if no keypress detected
840                 else
841                 {
842                         // If the key was previously pressed, remove from the buffer
843                         for ( uint8_t c = 0; c < KeyIndex_BufferUsed; c++ )
844                         {
845                                 // Key to release found
846                                 if ( KeyIndex_Buffer[c] == key )
847                                 {
848                                         // Shift keys from c position
849                                         for ( uint8_t k = c; k < KeyIndex_BufferUsed - 1; k++ )
850                                                 KeyIndex_Buffer[k] = KeyIndex_Buffer[k + 1];
851
852                                         // Decrement Buffer
853                                         KeyIndex_BufferUsed--;
854
855                                         break;
856                                 }
857                         }
858
859
860                         // Clear debounce entry
861                         keys_debounce[key] = 0;
862                 }
863
864                 bit <<= 1;
865         }
866 }
867
868
869 void dumpSenseTable()
870 {
871         // Initial table alignment, with base threshold used for every key
872         print("\033[1m");
873         printHex( threshold );
874         print("\033[0m       ");
875
876         // Print out headers first
877         for ( uint8_t mux = 0; mux < MUXES_COUNT; ++mux )
878         {
879                 print("  Mux \033[1m");
880                 printInt8( mux );
881                 print("\033[0m  ");
882         }
883
884         print( NL );
885
886         // Display the full strobe/sense table
887         for ( uint8_t strober = 0; strober < total_strobes; ++strober )
888         {
889                 uint8_t strobe = strobe_map[strober];
890
891                 // Display the strobe
892                 print("Strobe \033[1m");
893                 printHex( strobe );
894                 print("\033[0m ");
895
896                 // For each mux, display sense:threshold:delta
897                 for ( uint8_t mux = 0; mux < MUXES_COUNT; ++mux )
898                 {
899                         uint8_t delta = keys_averages[(strobe << MUXES_COUNT_XSHIFT) + mux];
900                         uint8_t sample = samples[strobe][mux] >> 1;
901                         uint8_t max = sampleMax[strobe][mux] >> 1;
902
903                         // Indicate if the key is being pressed by displaying green
904                         if ( sample > delta + threshold )
905                         {
906                                 print("\033[1;32m");
907                         }
908
909                         printHex_op( sample, 2 );
910                         print(":");
911                         printHex_op( max, 2 );
912                         print(":");
913                         printHex_op( delta, 2 );
914                         print("\033[0m ");
915                 }
916
917                 // New line for each strobe
918                 print( NL );
919         }
920 }
921
922
923 // ----- CLI Command Functions -----
924
925 // XXX Just an example command showing how to parse arguments (more complex than generally needed)
926 void cliFunc_echo( char* args )
927 {
928         char* curArgs;
929         char* arg1Ptr;
930         char* arg2Ptr = args;
931
932         // Parse args until a \0 is found
933         while ( 1 )
934         {
935                 print( NL ); // No \r\n by default after the command is entered
936
937                 curArgs = arg2Ptr; // Use the previous 2nd arg pointer to separate the next arg from the list
938                 CLI_argumentIsolation( curArgs, &arg1Ptr, &arg2Ptr );
939
940                 // Stop processing args if no more are found
941                 if ( *arg1Ptr == '\0' )
942                         break;
943
944                 // Print out the arg
945                 dPrint( arg1Ptr );
946         }
947 }
948
949 void cliFunc_avgDebug( char* args )
950 {
951         print( NL );
952
953         // Args ignored, just toggling
954         if ( enableAvgDebug )
955         {
956                 info_print("Cap Sense averaging debug disabled.");
957                 enableAvgDebug = 0;
958         }
959         else
960         {
961                 info_print("Cap Sense averaging debug enabled.");
962                 enableAvgDebug = 1;
963         }
964 }
965
966 void cliFunc_keyDebug( char* args )
967 {
968         print( NL );
969
970         // Args ignored, just toggling
971         if ( enableKeyDebug )
972         {
973                 info_print("Cap Sense key long debug disabled - pre debounce.");
974                 enableKeyDebug = 0;
975         }
976         else
977         {
978                 info_print("Cap Sense key long debug enabled - pre debounce.");
979                 enableKeyDebug = 1;
980         }
981 }
982
983 void cliFunc_pressDebug( char* args )
984 {
985         print( NL );
986
987         // Args ignored, just toggling
988         if ( enablePressDebug )
989         {
990                 info_print("Cap Sense key debug disabled - post debounce.");
991                 enablePressDebug = 0;
992         }
993         else
994         {
995                 info_print("Cap Sense key debug enabled - post debounce.");
996                 enablePressDebug = 1;
997         }
998 }
999
1000 void cliFunc_problemKeys( char* args )
1001 {
1002         print( NL );
1003
1004         uint8_t count = 0;
1005
1006         // Args ignored, just displaying
1007         // Display problem keys, and the sense value at the time
1008         for ( uint8_t key = 0; key < KEY_COUNT; key++ )
1009         {
1010                 if ( keys_problem[key] )
1011                 {
1012                         if ( count++ == 0 )
1013                         {
1014                                 warn_msg("Problem keys: ");
1015                         }
1016                         printHex( key );
1017                         print(" (");
1018                         printHex( keys_problem[key] );
1019                         print(")   "  );
1020                 }
1021         }
1022 }
1023
1024 void cliFunc_senseDebug( char* args )
1025 {
1026         // Parse code from argument
1027         //  NOTE: Only first argument is used
1028         char* arg1Ptr;
1029         char* arg2Ptr;
1030         CLI_argumentIsolation( args, &arg1Ptr, &arg2Ptr );
1031
1032         // Default to a single print
1033         senseDebugCount = 1;
1034
1035         // If there was an argument, use that instead
1036         if ( *arg1Ptr != '\0' )
1037         {
1038                 senseDebugCount = decToInt( arg1Ptr );
1039         }
1040 }
1041