]> git.donarmstrong.com Git - kiibohd-controller.git/blob - Scan/DPH/scan_loop.c
Enabling USB keycodes.
[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 char*       scanCLIDictName = "DPH Module Commands";
153 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_finishedWithBuffer( uint8_t sentKeys )
326 {
327         // Convenient place to clear the KeyIndex_Buffer
328         KeyIndex_BufferUsed = 0;
329         return;
330 }
331
332
333 // Signal KeyIndex_Buffer that it has been properly read and sent out by the USB module
334 // NOTE: Only really required for implementing "tricks" in converters for odd protocols
335 void Scan_finishedWithUSBBuffer( uint8_t sentKeys )
336 {
337         return;
338 }
339
340
341 inline void capsense_scan()
342 {
343         // Accumulated average used for the next scan
344         uint32_t cur_full_avg = 0;
345         uint32_t cur_high_avg = 0;
346
347         // Reset average counters
348         low_avg = 0;
349         low_count = 0;
350
351         high_count = 0;
352
353         // Reset key activity, if there is no key activity, averages will accumulate for sense deltas, otherwise they will be reset
354         key_activity = 0;
355
356         // Scan each of the mapped strobes in the matrix
357         for ( uint8_t strober = 0; strober < total_strobes; ++strober )
358         {
359                 uint8_t map_strobe = strobe_map[strober];
360
361                 // Sample the ADCs for the given column/strobe
362                 sampleColumn( map_strobe );
363
364                 // Only process sense data if warmup is finished
365                 if ( boot_count >= WARMUP_LOOPS )
366                 {
367                         testColumn( map_strobe );
368                 }
369
370                 uint8_t strobe_line = map_strobe << MUXES_COUNT_XSHIFT;
371                 for ( int mux = 0; mux < MUXES_COUNT; ++mux )
372                 {
373                         // discard sketchy low bit, and meaningless high bits.
374                         uint8_t sample = samples[map_strobe][mux] >> 1;
375                         keys_averages_acc[strobe_line + mux] += sample;
376                 }
377
378                 // Accumulate 3 total averages (used for determining starting average during warmup)
379                 //     full_avg - Average of all sampled lines on the previous scan set
380                 // cur_full_avg - Average of all sampled lines for this scan set
381                 //     high_avg - Average of all sampled lines above full_avg on the previous scan set
382                 // cur_high_avg - Average of all sampled lines above full_avg
383                 //      low_avg - Average of all sampled lines below or equal to full_avg
384                 if ( boot_count < WARMUP_LOOPS )
385                 {
386                         for ( uint8_t mux = 0; mux < MUXES_COUNT; ++mux )
387                         {
388                                 uint8_t sample = samples[map_strobe][mux] >> 1;
389
390                                 // Sample is high, add it to high avg
391                                 if ( sample > full_avg )
392                                 {
393                                         high_count++;
394                                         cur_high_avg += sample;
395                                 }
396                                 // Sample is low, add it to low avg
397                                 else
398                                 {
399                                         low_count++;
400                                         low_avg += sample;
401                                 }
402
403                                 // If sample is higher than previous high_avg, then mark as "problem key"
404                                 // XXX Giving a bit more margin to pass (high_avg vs. high_avg + high_avg - full_avg) -HaaTa
405                                 keys_problem[strobe_line + mux] = sample > high_avg + (high_avg - full_avg) ? sample : 0;
406
407                                 // Prepare for next average
408                                 cur_full_avg += sample;
409                         }
410                 }
411         } // for strober
412
413         // Update total sense average (only during warm-up)
414         if ( boot_count < WARMUP_LOOPS )
415         {
416                 full_avg = cur_full_avg / (total_strobes * MUXES_COUNT);
417                 high_avg = cur_high_avg / high_count;
418                 low_avg /= low_count;
419
420                 // Update the base average value using the low_avg (best chance of not ignoring a keypress)
421                 for ( int i = 0; i < KEY_COUNT; ++i )
422                 {
423                         keys_averages[i] = low_avg;
424                         keys_averages_acc[i] = low_avg;
425                 }
426         }
427
428         // Warm up voltage references
429         if ( boot_count < WARMUP_LOOPS )
430         {
431                 boot_count++;
432
433                 switch ( boot_count )
434                 {
435                 // First loop
436                 case 1:
437                         // Show msg at first iteration only
438                         info_msg("Warming up the voltage references");
439                         break;
440                 // Middle iterations
441                 case 300:
442                 case 600:
443                 case 900:
444                 case 1200:
445                         print(".");
446                         break;
447                 // Last loop
448                 case WARMUP_STOP:
449                         print( NL );
450                         info_msg("Warmup finished using ");
451                         printInt16( WARMUP_LOOPS );
452                         print(" iterations" NL );
453
454                         // Display the final calculated averages of all the sensed strobes
455                         info_msg("Full average (");
456                         printInt8( total_strobes * MUXES_COUNT );
457                         print("): ");
458                         printHex( full_avg );
459
460                         print("  High average (");
461                         printInt8( high_count );
462                         print("): ");
463                         printHex( high_avg );
464
465                         print("  Low average (");
466                         printInt8( low_count );
467                         print("): ");
468                         printHex( low_avg );
469
470                         print("  Rejection threshold: ");
471                         printHex( high_avg + (high_avg - full_avg) );
472                         print( NL );
473
474                         // Display problem keys, and the sense value at the time
475                         for ( uint8_t key = 0; key < KEY_COUNT; key++ )
476                         {
477                                 if ( keys_problem[key] )
478                                 {
479                                         warn_msg("Problem key detected: ");
480                                         printHex( key );
481                                         print(" (");
482                                         printHex( keys_problem[key] );
483                                         print(")" NL );
484                                 }
485                         }
486
487                         info_print("If problem keys were detected, and were being held down, they will be reset as soon as let go");
488                         break;
489                 }
490         }
491         else
492         {
493                 // No keypress, accumulate averages
494                 if( !key_activity )
495                 {
496                         // Only start averaging once the idle counter has counted down to 0
497                         if ( key_idle == 0 )
498                         {
499                                 // Average Debugging
500                                 if ( enableAvgDebug )
501                                 {
502                                         print("\033[1mAvg\033[0m: ");
503                                 }
504
505                                 // aggregate
506                                 for ( uint8_t i = 0; i < KEY_COUNT; ++i )
507                                 {
508                                         uint16_t acc = keys_averages_acc[i];
509                                         //uint16_t acc = keys_averages_acc[i] >> IDLE_COUNT_SHIFT; // XXX This fixes things... -HaaTa
510                                         uint32_t av = keys_averages[i];
511
512                                         av = (av << KEYS_AVERAGES_MIX_SHIFT) - av + acc;
513                                         av >>= KEYS_AVERAGES_MIX_SHIFT;
514
515                                         keys_averages[i] = av;
516                                         keys_averages_acc[i] = 0;
517
518                                         // Average Debugging
519                                         if ( enableAvgDebug && av > 0 )
520                                         {
521                                                 printHex( av );
522                                                 print(" ");
523                                         }
524                                 }
525
526                                 // Average Debugging
527                                 if ( enableAvgDebug )
528                                 {
529                                         print( NL );
530                                 }
531
532                                 // No key presses detected, set key_release indicator
533                                 key_release = 1;
534                         }
535                         // Otherwise decrement the idle counter
536                         else
537                         {
538                                 key_idle--;
539                         }
540                 }
541                 // Keypresses, reset accumulators
542                 else if ( key_release )
543                 {
544                         for ( uint8_t c = 0; c < KEY_COUNT; ++c ) { keys_averages_acc[c] = 0; }
545
546                         key_release = 0;
547                 }
548
549                 // If the debugging sense table is non-zero, display
550                 if ( senseDebugCount > 0 )
551                 {
552                         senseDebugCount--;
553                         print( NL );
554                         dumpSenseTable();
555                 }
556         }
557 }
558
559
560 void setup_ADC()
561 {
562         // disable adc digital pins.
563         DIDR1 |= (1 << AIN0D) | (1<<AIN1D); // set disable on pins 1,0.
564         DDRF = 0x0;
565         PORTF = 0x0;
566         uint8_t mux = 0 & 0x1f; // 0 == first. // 0x1e = 1.1V ref.
567
568         // 0 = external aref 1,1 = 2.56V internal ref
569         uint8_t aref = ((1 << REFS1) | (1 << REFS0)) & ((1 << REFS1) | (1 << REFS0));
570         uint8_t adate = (1 << ADATE) & (1 << ADATE); // trigger enable
571         uint8_t trig = 0 & ((1 << ADTS0) | (1 << ADTS1) | (1 << ADTS2)); // 0 = free running
572         // ps2, ps1 := /64 ( 2^6 ) ps2 := /16 (2^4), ps1 := 4, ps0 :=2, PS1,PS0 := 8 (2^8)
573         uint8_t prescale = ( ((PRESCALE) << PRESCALE_SHIFT) & PRESCALE_MASK ); // 001 == 2^1 == 2
574         uint8_t hispeed = (1 << ADHSM);
575         uint8_t en_mux = (1 << ACME);
576
577         ADCSRA = (1 << ADEN) | prescale; // ADC enable
578
579         // select ref.
580         //ADMUX |= ((1 << REFS1) | (1 << REFS0)); // 2.56 V internal.
581         //ADMUX |= ((1 << REFS0) ); // Vcc with external cap.
582         //ADMUX &= ~((1 << REFS1) | (1 << REFS0)); // 0,0 : aref.
583         ADMUX = aref | mux | ADLAR_BITS;
584
585         // set free-running
586         ADCSRA |= adate; // trigger enable
587         ADCSRB  = en_mux | hispeed | trig | (ADCSRB & ~((1 << ADTS0) | (1 << ADTS1) | (1 << ADTS2))); // trigger select free running
588
589         ADCSRA |= (1 << ADEN); // ADC enable
590         ADCSRA |= (1 << ADSC); // start conversions q
591 }
592
593
594 void recovery( uint8_t on )
595 {
596         DDRB  |=  (1 << RECOVERY_CONTROL);
597         PORTB &= ~(1 << RECOVERY_SINK);   // SINK always zero
598         DDRB  &= ~(1 << RECOVERY_SOURCE); // SOURCE high imp
599
600         if ( on )
601         {
602                 // set strobes to sink to gnd.
603                 DDRC |= C_MASK;
604                 DDRD |= D_MASK;
605                 DDRE |= E_MASK;
606
607                 PORTC &= ~C_MASK;
608                 PORTD &= ~D_MASK;
609                 PORTE &= ~E_MASK;
610
611                 DDRB  |= (1 << RECOVERY_SINK);   // SINK pull
612                 PORTB |= (1 << RECOVERY_CONTROL);
613                 PORTB |= (1 << RECOVERY_SOURCE); // SOURCE high
614                 DDRB  |= (1 << RECOVERY_SOURCE);
615         }
616         else
617         {
618                 PORTB &= ~(1 << RECOVERY_CONTROL);
619                 DDRB  &= ~(1 << RECOVERY_SOURCE);
620                 PORTB &= ~(1 << RECOVERY_SOURCE); // SOURCE low
621                 DDRB  &= ~(1 << RECOVERY_SINK);   // SINK high-imp
622         }
623 }
624
625
626 void hold_sample( uint8_t on )
627 {
628         if ( !on )
629         {
630                 PORTB |= (1 << SAMPLE_CONTROL);
631                 DDRB  |= (1 << SAMPLE_CONTROL);
632         }
633         else
634         {
635                 DDRB  |=  (1 << SAMPLE_CONTROL);
636                 PORTB &= ~(1 << SAMPLE_CONTROL);
637         }
638 }
639
640
641 void strobe_w( uint8_t strobe_num )
642 {
643         PORTC &= ~(C_MASK);
644         PORTD &= ~(D_MASK);
645         PORTE &= ~(E_MASK);
646
647         // Strobe table
648         // Not all strobes are used depending on which are detected
649         switch ( strobe_num )
650         {
651
652         case 0:  PORTD |= (1 << 0); break;
653         case 1:  PORTD |= (1 << 1); break;
654         case 2:  PORTD |= (1 << 2); break;
655         case 3:  PORTD |= (1 << 3); break;
656         case 4:  PORTD |= (1 << 4); break;
657         case 5:  PORTD |= (1 << 5); break;
658         case 6:  PORTD |= (1 << 6); break;
659         case 7:  PORTD |= (1 << 7); break;
660
661         case 8:  PORTE |= (1 << 0); break;
662         case 9:  PORTE |= (1 << 1); break;
663
664         case 10: PORTC |= (1 << 0); break;
665         case 11: PORTC |= (1 << 1); break;
666         case 12: PORTC |= (1 << 2); break;
667         case 13: PORTC |= (1 << 3); break;
668         case 14: PORTC |= (1 << 4); break;
669         case 15: PORTC |= (1 << 5); break;
670         case 16: PORTC |= (1 << 6); break;
671         case 17: PORTC |= (1 << 7); break;
672
673         default:
674                 break;
675         }
676 }
677
678
679 inline uint16_t getADC(void)
680 {
681         ADCSRA |= (1 << ADIF); // clear int flag by writing 1.
682
683         //wait for last read to complete.
684         while ( !( ADCSRA & (1 << ADIF) ) );
685
686         return ADC; // return sample
687 }
688
689
690 void sampleColumn( uint8_t column )
691 {
692         // ensure all probe lines are driven low, and chill for recovery delay.
693         ADCSRA |= (1 << ADEN) | (1 << ADSC); // enable and start conversions
694
695         PORTC &= ~C_MASK;
696         PORTD &= ~D_MASK;
697         PORTE &= ~E_MASK;
698
699         PORTF = 0;
700         DDRF  = 0;
701
702         recovery( OFF );
703         strobe_w( column );
704
705         hold_sample( OFF );
706         SET_FULL_MUX( 0 );
707
708         // Allow strobes to settle
709         for ( uint8_t i = 0; i < STROBE_SETTLE; ++i ) { getADC(); }
710
711         hold_sample( ON );
712
713         uint8_t mux = 0;
714         SET_FULL_MUX( mux );
715         getADC(); // throw away; unknown mux.
716         do {
717                 SET_FULL_MUX( mux + 1 ); // our *next* sample will use this
718
719                 // retrieve current read.
720                 uint16_t readVal = getADC();
721                 samples[column][mux] = readVal;
722
723                 // Update max sense sample table
724                 if ( readVal > sampleMax[column][mux] )
725                 {
726                         sampleMax[column][mux] = readVal;
727                 }
728
729                 mux++;
730
731         } while ( mux < 8 );
732
733         hold_sample( OFF );
734         recovery( ON );
735
736         // turn off adc.
737         ADCSRA &= ~(1 << ADEN);
738
739         // pull all columns' strobe-lines low.
740         DDRC |= C_MASK;
741         DDRD |= D_MASK;
742         DDRE |= E_MASK;
743
744         PORTC &= ~C_MASK;
745         PORTD &= ~D_MASK;
746         PORTE &= ~E_MASK;
747 }
748
749
750 void testColumn( uint8_t strobe )
751 {
752         uint16_t db_delta = 0;
753         uint8_t  db_sample = 0;
754         uint16_t db_threshold = 0;
755
756         uint8_t column = 0;
757         uint8_t bit = 1;
758
759         for ( uint8_t mux = 0; mux < MUXES_COUNT; ++mux )
760         {
761                 uint16_t delta = keys_averages[(strobe << MUXES_COUNT_XSHIFT) + mux];
762
763                 uint8_t key = (strobe << MUXES_COUNT_XSHIFT) + mux;
764
765                 // Check if this is a bad key (e.g. test point, or non-existent key)
766                 if ( keys_problem[key] )
767                 {
768                         // If the sample value of the problem key goes below full_avg (overall initial average)
769                         //  re-enable the key
770                         if ( (db_sample = samples[strobe][mux] >> 1) < full_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                                         // Only add the key to the buffer once
807                                         // NOTE: Buffer can easily handle multiple adds, just more efficient
808                                         //        and nicer debug messages :P
809                                         Macro_bufferAdd( key );
810                                 }
811
812                                 keys_debounce[key]++;
813
814                         }
815
816                         // Long form key debugging
817                         if ( enableKeyDebug )
818                         {
819                                 // Debug message
820                                 // <key> [<strobe>:<mux>] : <sense val> : <delta + threshold> : <margin>
821                                 dbug_msg("0x");
822                                 printHex_op( key, 2 );
823                                 print(" [");
824                                 printInt8( strobe );
825                                 print(":");
826                                 printInt8( mux );
827                                 print("] : ");
828                                 printHex( db_sample ); // Sense
829                                 print(" : ");
830                                 printHex( db_threshold );
831                                 print("+");
832                                 printHex( db_delta );
833                                 print("=");
834                                 printHex( db_threshold + db_delta ); // Sense compare
835                                 print(" : ");
836                                 printHex( db_sample - ( db_threshold + db_delta ) ); // Margin
837                                 print( NL );
838                         }
839                 }
840                 // Clear debounce entry if no keypress detected
841                 else
842                 {
843                         // If the key was previously pressed, remove from the buffer
844                         for ( uint8_t c = 0; c < KeyIndex_BufferUsed; c++ )
845                         {
846                                 // Key to release found
847                                 if ( KeyIndex_Buffer[c] == key )
848                                 {
849                                         // Shift keys from c position
850                                         for ( uint8_t k = c; k < KeyIndex_BufferUsed - 1; k++ )
851                                                 KeyIndex_Buffer[k] = KeyIndex_Buffer[k + 1];
852
853                                         // Decrement Buffer
854                                         KeyIndex_BufferUsed--;
855
856                                         break;
857                                 }
858                         }
859
860
861                         // Clear debounce entry
862                         keys_debounce[key] = 0;
863                 }
864
865                 bit <<= 1;
866         }
867 }
868
869
870 void dumpSenseTable()
871 {
872         // Initial table alignment, with base threshold used for every key
873         print("\033[1m");
874         printHex( threshold );
875         print("\033[0m       ");
876
877         // Print out headers first
878         for ( uint8_t mux = 0; mux < MUXES_COUNT; ++mux )
879         {
880                 print("  Mux \033[1m");
881                 printInt8( mux );
882                 print("\033[0m  ");
883         }
884
885         print( NL );
886
887         // Display the full strobe/sense table
888         for ( uint8_t strober = 0; strober < total_strobes; ++strober )
889         {
890                 uint8_t strobe = strobe_map[strober];
891
892                 // Display the strobe
893                 print("Strobe \033[1m");
894                 printHex( strobe );
895                 print("\033[0m ");
896
897                 // For each mux, display sense:threshold:delta
898                 for ( uint8_t mux = 0; mux < MUXES_COUNT; ++mux )
899                 {
900                         uint8_t delta = keys_averages[(strobe << MUXES_COUNT_XSHIFT) + mux];
901                         uint8_t sample = samples[strobe][mux] >> 1;
902                         uint8_t max = sampleMax[strobe][mux] >> 1;
903
904                         // Indicate if the key is being pressed by displaying green
905                         if ( sample > delta + threshold )
906                         {
907                                 print("\033[1;32m");
908                         }
909
910                         printHex_op( sample, 2 );
911                         print(":");
912                         printHex_op( max, 2 );
913                         print(":");
914                         printHex_op( delta, 2 );
915                         print("\033[0m ");
916                 }
917
918                 // New line for each strobe
919                 print( NL );
920         }
921 }
922
923
924 // ----- CLI Command Functions -----
925
926 // XXX Just an example command showing how to parse arguments (more complex than generally needed)
927 void cliFunc_echo( char* args )
928 {
929         char* curArgs;
930         char* arg1Ptr;
931         char* arg2Ptr = args;
932
933         // Parse args until a \0 is found
934         while ( 1 )
935         {
936                 print( NL ); // No \r\n by default after the command is entered
937
938                 curArgs = arg2Ptr; // Use the previous 2nd arg pointer to separate the next arg from the list
939                 CLI_argumentIsolation( curArgs, &arg1Ptr, &arg2Ptr );
940
941                 // Stop processing args if no more are found
942                 if ( *arg1Ptr == '\0' )
943                         break;
944
945                 // Print out the arg
946                 dPrint( arg1Ptr );
947         }
948 }
949
950 void cliFunc_avgDebug( char* args )
951 {
952         print( NL );
953
954         // Args ignored, just toggling
955         if ( enableAvgDebug )
956         {
957                 info_print("Cap Sense averaging debug disabled.");
958                 enableAvgDebug = 0;
959         }
960         else
961         {
962                 info_print("Cap Sense averaging debug enabled.");
963                 enableAvgDebug = 1;
964         }
965 }
966
967 void cliFunc_keyDebug( char* args )
968 {
969         print( NL );
970
971         // Args ignored, just toggling
972         if ( enableKeyDebug )
973         {
974                 info_print("Cap Sense key long debug disabled - pre debounce.");
975                 enableKeyDebug = 0;
976         }
977         else
978         {
979                 info_print("Cap Sense key long debug enabled - pre debounce.");
980                 enableKeyDebug = 1;
981         }
982 }
983
984 void cliFunc_pressDebug( char* args )
985 {
986         print( NL );
987
988         // Args ignored, just toggling
989         if ( enablePressDebug )
990         {
991                 info_print("Cap Sense key debug disabled - post debounce.");
992                 enablePressDebug = 0;
993         }
994         else
995         {
996                 info_print("Cap Sense key debug enabled - post debounce.");
997                 enablePressDebug = 1;
998         }
999 }
1000
1001 void cliFunc_problemKeys( char* args )
1002 {
1003         print( NL );
1004
1005         uint8_t count = 0;
1006
1007         // Args ignored, just displaying
1008         // Display problem keys, and the sense value at the time
1009         for ( uint8_t key = 0; key < KEY_COUNT; key++ )
1010         {
1011                 if ( keys_problem[key] )
1012                 {
1013                         if ( count++ == 0 )
1014                         {
1015                                 warn_msg("Problem keys: ");
1016                         }
1017                         printHex( key );
1018                         print(" (");
1019                         printHex( keys_problem[key] );
1020                         print(")   "  );
1021                 }
1022         }
1023 }
1024
1025 void cliFunc_senseDebug( char* args )
1026 {
1027         // Parse code from argument
1028         //  NOTE: Only first argument is used
1029         char* arg1Ptr;
1030         char* arg2Ptr;
1031         CLI_argumentIsolation( args, &arg1Ptr, &arg2Ptr );
1032
1033         // Default to a single print
1034         senseDebugCount = 1;
1035
1036         // If there was an argument, use that instead
1037         if ( *arg1Ptr != '\0' )
1038         {
1039                 senseDebugCount = decToInt( arg1Ptr );
1040         }
1041 }
1042