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