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