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