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