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