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