]> git.donarmstrong.com Git - kiibohd-controller.git/blob - Scan/avr-capsense/scan_loop.c
Added the averaged initial average as well as problem key rejection
[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 TERMINAL_6110668_STROBE
218 //#define UNSAVER_STROBE
219 #ifdef KISHSAVER_STROBE
220         total_strobes = 8;
221
222         strobe_map[0] = 2; // Kishsaver doesn't use strobe 0 and 1
223         strobe_map[1] = 3;
224         strobe_map[2] = 4;
225         strobe_map[3] = 5;
226         strobe_map[4] = 6;
227         strobe_map[5] = 7;
228         strobe_map[6] = 8;
229         strobe_map[7] = 9;
230         // XXX - Disabling for now, not sure how to deal with test points yet (without spamming the debug)
231         total_strobes = 9;
232         strobe_map[8] = 15; // Test point strobe (3 test points, sense 1, 4, 5)
233 #elif defined(TERMINAL_6110668_STROBE)
234         total_strobes = 16;
235
236         strobe_map[0] = 0;
237         strobe_map[1] = 1;
238         strobe_map[2] = 2;
239         strobe_map[3] = 3;
240         strobe_map[4] = 4;
241         strobe_map[5] = 5;
242         strobe_map[6] = 6;
243         strobe_map[7] = 7;
244         strobe_map[8] = 8;
245         strobe_map[9] = 9;
246         strobe_map[10] = 10;
247         strobe_map[11] = 11;
248         strobe_map[12] = 12;
249         strobe_map[13] = 13;
250         strobe_map[14] = 14;
251         strobe_map[15] = 15;
252 #elif defined(UNSAVER_STROBE)
253         total_strobes = 14;
254
255         strobe_map[0] = 0;
256         strobe_map[1] = 1;
257         strobe_map[2] = 2;
258         strobe_map[3] = 3;
259         strobe_map[4] = 4;
260         strobe_map[5] = 5;
261         strobe_map[6] = 6;
262         strobe_map[7] = 7;
263         strobe_map[8] = 8;
264         strobe_map[9] = 9;
265         strobe_map[10] = 10;
266         strobe_map[11] = 11;
267         strobe_map[12] = 12;
268         strobe_map[13] = 13;
269 #else
270         // Strobe detection
271         // TODO
272 #endif
273
274         // TODO all this code should probably be in scan_resetKeyboard
275         for ( int i = 0; i < total_strobes; ++i)
276         {
277                 cur_keymap[i] = 0;
278         }
279
280         // Reset debounce table
281         for ( int i = 0; i < KEY_COUNT; ++i )
282         {
283                 keys_debounce[i] = 0;
284         }
285
286         // Warm things up a bit before we start collecting data, taking real samples.
287         for ( uint8_t i = 0; i < total_strobes; ++i )
288         {
289                 sampleColumn( strobe_map[i] );
290         }
291
292
293         // Reset the keyboard before scanning, we might be in a wierd state
294         // Also sets the KeyIndex_BufferUsed to 0
295         scan_resetKeyboard();
296 }
297
298
299 // Main Detection Loop
300 // This is where the important stuff happens
301 inline uint8_t scan_loop()
302 {
303         capsense_scan();
304
305         // Error case, should not occur in normal operation
306         if ( error )
307         {
308                 erro_msg("Problem detected... ");
309
310                 // Keymap scan debug
311                 for ( uint8_t i = 0; i < total_strobes; ++i )
312                 {
313                         printHex(cur_keymap[strobe_map[i]]);
314                         print(" ");
315                 }
316
317                 print(" : ");
318                 printHex(error);
319                 error = 0;
320                 print(" : ");
321                 printHex(error_data);
322                 error_data = 0;
323
324                 // Display keymaps and other debug information if warmup completede
325                 if ( boot_count >= WARMUP_LOOPS )
326                 {
327                         dump();
328                 }
329         }
330
331
332         // Return non-zero if macro and USB processing should be delayed
333         // Macro processing will always run if returning 0
334         // USB processing only happens once the USB send timer expires, if it has not, scan_loop will be called
335         //  after the macro processing has been completed
336         return 0;
337 }
338
339
340 // Reset Keyboard
341 void scan_resetKeyboard( void )
342 {
343         // Empty buffer, now that keyboard has been reset
344         KeyIndex_BufferUsed = 0;
345 }
346
347
348 // Send data to keyboard
349 // NOTE: Only used for converters, since the scan module shouldn't handle sending data in a controller
350 uint8_t scan_sendData( uint8_t dataPayload )
351 {
352         return 0;
353 }
354
355
356 // Reset/Hold keyboard
357 // NOTE: Only used for converters, not needed for full controllers
358 void scan_lockKeyboard( void )
359 {
360 }
361
362 // NOTE: Only used for converters, not needed for full controllers
363 void scan_unlockKeyboard( void )
364 {
365 }
366
367
368 // Signal KeyIndex_Buffer that it has been properly read
369 // NOTE: Only really required for implementing "tricks" in converters for odd protocols
370 void scan_finishedWithBuffer( uint8_t sentKeys )
371 {
372         // Convenient place to clear the KeyIndex_Buffer
373         KeyIndex_BufferUsed = 0;
374         return;
375 }
376
377
378 // Signal KeyIndex_Buffer that it has been properly read and sent out by the USB module
379 // NOTE: Only really required for implementing "tricks" in converters for odd protocols
380 void scan_finishedWithUSBBuffer( uint8_t sentKeys )
381 {
382         return;
383 }
384
385
386 inline void capsense_scan()
387 {
388         // Accumulated average used for the next scan
389         uint32_t cur_full_avg = 0;
390         uint32_t cur_high_avg = 0;
391
392         // Reset average counters
393         low_avg = 0;
394         low_count = 0;
395
396         high_count = 0;
397
398         // Scan each of the mapped strobes in the matrix
399         for ( uint8_t strober = 0; strober < total_strobes; ++strober )
400         {
401                 uint8_t map_strobe = strobe_map[strober];
402
403                 uint8_t tries = 1;
404                 while ( tries++ && sampleColumn( map_strobe ) ) { tries &= 0x7; } // don't waste this one just because the last one was poop.
405
406                 // Only process sense data if warmup is finished
407                 if ( boot_count >= WARMUP_LOOPS )
408                 {
409                         column = testColumn( map_strobe );
410
411                         idle |= column; // if column has any pressed keys, then we are not idle.
412
413                         // TODO Is this needed anymore? Really only helps debug -HaaTa
414                         if( column != cur_keymap[map_strobe] && ( boot_count >= WARMUP_LOOPS ) )
415                         {
416                                 cur_keymap[map_strobe] = column;
417                                 keymap_change = 1;
418                         }
419
420                         idle |= keymap_change; // if any keys have changed inc. released, then we are not idle.
421                 }
422
423                 if ( error == 0x50 )
424                 {
425                         error_data |= (((uint16_t)map_strobe) << 12);
426                 }
427
428                 uint8_t strobe_line = map_strobe << MUXES_COUNT_XSHIFT;
429                 for ( int i = 0; i < MUXES_COUNT; ++i )
430                 {
431                         // discard sketchy low bit, and meaningless high bits.
432                         uint8_t sample = samples[i] >> 1;
433                         full_samples[strobe_line + i] = sample;
434                         keys_averages_acc[strobe_line + i] += sample;
435                 }
436
437                 // Accumulate 3 total averages (used for determining starting average during warmup)
438                 //     full_avg - Average of all sampled lines on the previous scan set
439                 // cur_full_avg - Average of all sampled lines for this scan set
440                 //     high_avg - Average of all sampled lines above full_avg on the previous scan set
441                 // cur_high_avg - Average of all sampled lines above full_avg
442                 //      low_avg - Average of all sampled lines below or equal to full_avg
443                 if ( boot_count < WARMUP_LOOPS )
444                 {
445                         for ( uint8_t i = 0; i < MUXES_COUNT; ++i )
446                         {
447                                 uint8_t sample = samples[i] >> 1;
448
449                                 // Sample is high, add it to high avg
450                                 if ( sample > full_avg )
451                                 {
452                                         high_count++;
453                                         cur_high_avg += sample;
454                                 }
455                                 // Sample is low, add it to low avg
456                                 else
457                                 {
458                                         low_count++;
459                                         low_avg += sample;
460                                 }
461
462                                 // If sample is higher than previous high_avg, then mark as "problem key"
463                                 keys_problem[strobe_line + i] = sample > high_avg ? sample : 0;
464
465                                 // Prepare for next average
466                                 cur_full_avg += sample;
467                         }
468                 }
469         } // for strober
470
471         // Update total sense average (only during warm-up)
472         if ( boot_count < WARMUP_LOOPS )
473         {
474                 full_avg = cur_full_avg / (total_strobes * MUXES_COUNT);
475                 high_avg = cur_high_avg / high_count;
476                 low_avg /= low_count;
477
478                 // Update the base average value using the low_avg (best chance of not ignoring a keypress)
479                 for ( int i = 0; i < KEY_COUNT; ++i )
480                 {
481                         keys_averages[i] = low_avg;
482                         keys_averages_acc[i] = low_avg;
483                 }
484         }
485
486 #ifdef VERIFY_TEST_PAD
487         // verify test key is not down.
488         if ( ( cur_keymap[TEST_KEY_STROBE] & TEST_KEY_MASK ) )
489         {
490                 error = 0x05;
491                 error_data = cur_keymap[TEST_KEY_STROBE] << 8;
492                 error_data += full_samples[TEST_KEY_STROBE * 8];
493         }
494 #endif
495
496         /** aggregate if booting, or if idle;
497          * else, if not booting, check for dirty USB.
498          * */
499
500         idle_count++;
501         idle_count &= IDLE_COUNT_MASK;
502
503         // Warm up voltage references
504         if ( boot_count < WARMUP_LOOPS )
505         {
506                 boot_count++;
507
508                 switch ( boot_count )
509                 {
510                 // First loop
511                 case 1:
512                         // Show msg at first iteration only
513                         info_msg("Warming up the voltage references");
514                         break;
515                 // Middle iterations
516                 case 300:
517                 case 600:
518                 case 900:
519                 case 1200:
520                         print(".");
521                         break;
522                 // Last loop
523                 case WARMUP_STOP:
524                         print("\n");
525                         info_msg("Warmup finished using ");
526                         printInt16( WARMUP_LOOPS );
527                         print(" iterations\n");
528
529                         // Display the final calculated averages of all the sensed strobes
530                         info_msg("Full average (");
531                         printInt8( total_strobes * MUXES_COUNT );
532                         print("): ");
533                         printHex( full_avg );
534
535                         print("  High average (");
536                         printInt8( high_count );
537                         print("): ");
538                         printHex( high_avg );
539
540                         print("  Low average (");
541                         printInt8( low_count );
542                         print("): ");
543                         printHex( low_avg );
544                         print("\n");
545
546                         // Display problem keys, and the sense value at the time
547                         for ( uint8_t key = 0; key < KEY_COUNT; key++ )
548                         {
549                                 if ( keys_problem[key] )
550                                 {
551                                         warn_msg("Problem key detected: ");
552                                         printHex( key );
553                                         print(" (");
554                                         printHex( keys_problem[key] );
555                                         print(")\n");
556                                 }
557                         }
558
559                         info_print("If problem keys were detected, and were being held down, they will be reset as soon as let go");
560                         break;
561                 }
562         }
563         else
564         {
565                 // Reset accumulators and idle flag/counter
566                 if ( keymap_change )
567                 {
568                         for ( uint8_t c = 0; c < KEY_COUNT; ++c ) { keys_averages_acc[c] = 0; }
569                         idle_count = 0;
570                         idle = 0;
571
572                         keymap_change = 0;
573                 }
574
575                 if ( !idle_count )
576                 {
577                         if( idle )
578                         {
579                                 // aggregate
580                                 for ( uint8_t i = 0; i < KEY_COUNT; ++i )
581                                 {
582                                         uint16_t acc = keys_averages_acc[i] >> IDLE_COUNT_SHIFT;
583                                         uint32_t av = keys_averages[i];
584
585                                         av = (av << KEYS_AVERAGES_MIX_SHIFT) - av + acc;
586                                         av >>= KEYS_AVERAGES_MIX_SHIFT;
587
588                                         keys_averages[i] = av;
589                                         keys_averages_acc[i] = 0;
590                                 }
591                         }
592
593                         if ( boot_count >= WARMUP_LOOPS )
594                         {
595                                 dump();
596                         }
597                 }
598
599         }
600 }
601
602
603 void setup_ADC()
604 {
605         // disable adc digital pins.
606         DIDR1 |= (1 << AIN0D) | (1<<AIN1D); // set disable on pins 1,0.
607         DDRF = 0x0;
608         PORTF = 0x0;
609         uint8_t mux = 0 & 0x1f; // 0 == first. // 0x1e = 1.1V ref.
610
611         // 0 = external aref 1,1 = 2.56V internal ref
612         uint8_t aref = ((1 << REFS1) | (1 << REFS0)) & ((1 << REFS1) | (1 << REFS0));
613         uint8_t adate = (1 << ADATE) & (1 << ADATE); // trigger enable
614         uint8_t trig = 0 & ((1 << ADTS0) | (1 << ADTS1) | (1 << ADTS2)); // 0 = free running
615         // ps2, ps1 := /64 ( 2^6 ) ps2 := /16 (2^4), ps1 := 4, ps0 :=2, PS1,PS0 := 8 (2^8)
616         uint8_t prescale = ( ((PRESCALE) << PRESCALE_SHIFT) & PRESCALE_MASK ); // 001 == 2^1 == 2
617         uint8_t hispeed = (1 << ADHSM);
618         uint8_t en_mux = (1 << ACME);
619
620         ADCSRA = (1 << ADEN) | prescale; // ADC enable
621
622         // select ref.
623         //ADMUX |= ((1 << REFS1) | (1 << REFS0)); // 2.56 V internal.
624         //ADMUX |= ((1 << REFS0) ); // Vcc with external cap.
625         //ADMUX &= ~((1 << REFS1) | (1 << REFS0)); // 0,0 : aref.
626         ADMUX = aref | mux | ADLAR_BITS;
627
628         // set free-running
629         ADCSRA |= adate; // trigger enable
630         ADCSRB  = en_mux | hispeed | trig | (ADCSRB & ~((1 << ADTS0) | (1 << ADTS1) | (1 << ADTS2))); // trigger select free running
631
632         ADCSRA |= (1 << ADEN); // ADC enable
633         ADCSRA |= (1 << ADSC); // start conversions q
634 }
635
636
637 void recovery( uint8_t on )
638 {
639         DDRB  |=  (1 << RECOVERY_CONTROL);
640         PORTB &= ~(1 << RECOVERY_SINK);   // SINK always zero
641         DDRB  &= ~(1 << RECOVERY_SOURCE); // SOURCE high imp
642
643         if ( on )
644         {
645                 // set strobes to sink to gnd.
646                 DDRC |= C_MASK;
647                 DDRD |= D_MASK;
648                 DDRE |= E_MASK;
649
650                 PORTC &= ~C_MASK;
651                 PORTD &= ~D_MASK;
652                 PORTE &= ~E_MASK;
653
654                 DDRB  |= (1 << RECOVERY_SINK);   // SINK pull
655                 PORTB |= (1 << RECOVERY_CONTROL);
656                 PORTB |= (1 << RECOVERY_SOURCE); // SOURCE high
657                 DDRB  |= (1 << RECOVERY_SOURCE);
658         }
659         else
660         {
661                 PORTB &= ~(1 << RECOVERY_CONTROL);
662                 DDRB  &= ~(1 << RECOVERY_SOURCE);
663                 PORTB &= ~(1 << RECOVERY_SOURCE); // SOURCE low
664                 DDRB  &= ~(1 << RECOVERY_SINK);   // SINK high-imp
665         }
666 }
667
668
669 void hold_sample( uint8_t on )
670 {
671         if ( !on )
672         {
673                 PORTB |= (1 << SAMPLE_CONTROL);
674                 DDRB  |= (1 << SAMPLE_CONTROL);
675         }
676         else
677         {
678                 DDRB  |=  (1 << SAMPLE_CONTROL);
679                 PORTB &= ~(1 << SAMPLE_CONTROL);
680         }
681 }
682
683
684 void strobe_w( uint8_t strobe_num )
685 {
686         PORTC &= ~(C_MASK);
687         PORTD &= ~(D_MASK);
688         PORTE &= ~(E_MASK);
689
690         // Strobe table
691         // Not all strobes are used depending on which are detected
692         switch ( strobe_num )
693         {
694
695         case 0:  PORTD |= (1 << 0); break;
696         case 1:  PORTD |= (1 << 1); break;
697         case 2:  PORTD |= (1 << 2); break;
698         case 3:  PORTD |= (1 << 3); break;
699         case 4:  PORTD |= (1 << 4); break;
700         case 5:  PORTD |= (1 << 5); break;
701         case 6:  PORTD |= (1 << 6); break;
702         case 7:  PORTD |= (1 << 7); break;
703
704         case 8:  PORTE |= (1 << 0); break;
705         case 9:  PORTE |= (1 << 1); break;
706
707         case 10: PORTC |= (1 << 0); break;
708         case 11: PORTC |= (1 << 1); break;
709         case 12: PORTC |= (1 << 2); break;
710         case 13: PORTC |= (1 << 3); break;
711         case 14: PORTC |= (1 << 4); break;
712         case 15: PORTC |= (1 << 5); break;
713         case 16: PORTC |= (1 << 6); break;
714         case 17: PORTC |= (1 << 7); break;
715
716         default:
717                 break;
718         }
719 }
720
721
722 inline uint16_t getADC(void)
723 {
724         ADCSRA |= (1 << ADIF); // clear int flag by writing 1.
725
726         //wait for last read to complete.
727         while ( !( ADCSRA & (1 << ADIF) ) );
728
729         return ADC; // return sample
730 }
731
732
733 int sampleColumn_8x( uint8_t column, uint16_t * buffer )
734 {
735         // ensure all probe lines are driven low, and chill for recovery delay.
736         ADCSRA |= (1 << ADEN) | (1 << ADSC); // enable and start conversions
737
738         PORTC &= ~C_MASK;
739         PORTD &= ~D_MASK;
740         PORTE &= ~E_MASK;
741
742         PORTF = 0;
743         DDRF  = 0;
744
745         recovery(OFF);
746         strobe_w(column);
747
748         hold_sample(OFF);
749         SET_FULL_MUX(0);
750
751         for ( uint8_t i = 0; i < STROBE_SETTLE; ++i ) { getADC(); }
752
753         hold_sample(ON);
754
755         uint8_t mux = 0;
756         SET_FULL_MUX(mux);
757         getADC(); // throw away; unknown mux.
758         do {
759                 SET_FULL_MUX(mux + 1); // our *next* sample will use this
760
761                 // retrieve current read.
762                 buffer[mux] = getADC();
763                 mux++;
764
765         } while (mux < 8);
766
767         hold_sample(OFF);
768         recovery(ON);
769
770         // turn off adc.
771         ADCSRA &= ~(1 << ADEN);
772
773         // pull all columns' strobe-lines low.
774         DDRC |= C_MASK;
775         DDRD |= D_MASK;
776         DDRE |= E_MASK;
777
778         PORTC &= ~C_MASK;
779         PORTD &= ~D_MASK;
780         PORTE &= ~E_MASK;
781
782         return 0;
783 }
784
785
786 int sampleColumn( uint8_t column )
787 {
788         int rval = 0;
789
790         rval = sampleColumn_8x( column, samples );
791
792         return rval;
793 }
794
795
796 uint8_t testColumn( uint8_t strobe )
797 {
798         uint16_t db_delta = 0;
799         uint8_t  db_sample = 0;
800         uint16_t db_threshold = 0;
801
802         uint8_t column = 0;
803         uint8_t bit = 1;
804
805         for ( uint8_t mux = 0; mux < MUXES_COUNT; ++mux )
806         {
807                 uint16_t delta = keys_averages[(strobe << MUXES_COUNT_XSHIFT) + mux];
808
809                 uint8_t key = (strobe << MUXES_COUNT_XSHIFT) + mux;
810
811                 // Check if this is a bad key (e.g. test point, or non-existent key)
812                 if ( keys_problem[key] )
813                 {
814                         // If the sample value of the problem key goes below full_avg (overall initial average)
815                         //  re-enable the key
816                         if ( (db_sample = samples[mux] >> 1) < full_avg )
817                         {
818                                 info_msg("Re-enabling problem key: ");
819                                 printHex( key );
820                                 print("\n");
821
822                                 keys_problem[key] = 0;
823                         }
824                         // Otherwise, don't waste any more cycles processing the problem key
825                         else
826                         {
827                                 continue;
828                         }
829                 }
830
831                 // Keypress detected
832                 //  db_sample (uint8_t), discard meaningless high bit, and garbage low bit
833                 if ( (db_sample = samples[mux] >> 1) > (db_threshold = threshold) + (db_delta = delta) )
834                 {
835                         column |= bit;
836
837                         // Only register keypresses once the warmup is complete, or not enough debounce info
838                         if ( keys_debounce[key] <= DEBOUNCE_THRESHOLD )
839                         {
840                                 // Add to the Macro processing buffer if debounce criteria met
841                                 // Automatically handles converting to a USB code and sending off to the PC
842                                 if ( keys_debounce[key] == DEBOUNCE_THRESHOLD )
843                                 {
844 //#define KEYSCAN_DEBOUNCE_DEBUG
845 #ifdef KEYSCAN_DEBOUNCE_DEBUG
846                                         // Debug message
847                                         print("0x");
848                                         printHex_op( key, 2 );
849                                         print(" ");
850 #endif
851
852                                         // Only add the key to the buffer once
853                                         // NOTE: Buffer can easily handle multiple adds, just more efficient
854                                         //        and nicer debug messages :P
855                                         //bufferAdd( key );
856                                 }
857
858                                 keys_debounce[key]++;
859
860 #define KEYSCAN_THRESHOLD_DEBUG
861 #ifdef KEYSCAN_THRESHOLD_DEBUG
862                                 // Debug message
863                                 // <key> [<strobe>:<mux>] : <sense val> : <delta + threshold> : <margin>
864                                 dbug_msg("0x");
865                                 printHex_op( key, 2 );
866                                 print(" [");
867                                 printInt8( strobe );
868                                 print(":");
869                                 printInt8( mux );
870                                 print("] : ");
871                                 printHex( db_sample ); // Sense
872                                 print(" : ");
873                                 printHex( db_threshold );
874                                 print("+");
875                                 printHex( db_delta );
876                                 print("=");
877                                 printHex( db_threshold + db_delta ); // Sense compare
878                                 print(" : ");
879                                 printHex( db_sample - ( db_threshold + db_delta ) ); // Margin
880                                 print("\n");
881 #endif
882                         }
883                 }
884                 // Clear debounce entry if no keypress detected
885                 else
886                 {
887                         // If the key was previously pressed, remove from the buffer
888                         for ( uint8_t c = 0; c < KeyIndex_BufferUsed; c++ )
889                         {
890                                 // Key to release found
891                                 if ( KeyIndex_Buffer[c] == key )
892                                 {
893                                         // Shift keys from c position
894                                         for ( uint8_t k = c; k < KeyIndex_BufferUsed - 1; k++ )
895                                                 KeyIndex_Buffer[k] = KeyIndex_Buffer[k + 1];
896
897                                         // Decrement Buffer
898                                         KeyIndex_BufferUsed--;
899
900                                         break;
901                                 }
902                         }
903
904
905                         // Clear debounce entry
906                         keys_debounce[key] = 0;
907                 }
908
909                 bit <<= 1;
910         }
911         return column;
912 }
913
914
915 void dump(void) {
916
917 #ifdef DEBUG_FULL_SAMPLES_AVERAGES
918         // we don't want to debug-out during the measurements.
919         if ( !dump_count )
920         {
921                 // Averages currently set per key
922                 for ( int i = 0; i < KEY_COUNT; ++i )
923                 {
924                         if ( !(i & 0x0f) )
925                         {
926                                 print("\n");
927                         }
928                         else if ( !(i & 0x07) )
929                         {
930                                 print("  ");
931                         }
932
933                         print(" ");
934                         printHex( keys_averages[i] );
935                 }
936
937                 print("\n");
938
939                 // Previously read full ADC scans?
940                 for ( int i = 0; i< KEY_COUNT; ++i)
941                 {
942                         if ( !(i & 0x0f) )
943                         {
944                                 print("\n");
945                         }
946                         else if ( !(i & 0x07) )
947                         {
948                                 print("  ");
949                         }
950
951                         print(" ");
952                         printHex(full_samples[i]);
953                 }
954         }
955 #endif
956
957 #ifdef DEBUG_STROBE_SAMPLES_AVERAGES
958         // Per strobe information
959         uint8_t cur_strober = ze_strober;
960         print("\n");
961
962         printHex(cur_strober);
963
964         // Previously read ADC scans on current strobe
965         print(" :");
966         for ( uint8_t i = 0; i < MUXES_COUNT; ++i )
967         {
968                 print(" ");
969                 printHex(full_samples[(cur_strober << MUXES_COUNT_XSHIFT) + i]);
970         }
971
972         // Averages current set on current strobe
973         print(" :");
974
975         for ( uint8_t i = 0; i < MUXES_COUNT; ++i )
976         {
977                 print(" ");
978                 printHex(keys_averages[(cur_strober << MUXES_COUNT_XSHIFT) + i]);
979         }
980
981 #endif
982
983 #ifdef DEBUG_USB_KEYMAP
984         print("\n      ");
985
986         // Current keymap values
987         for ( uint8_t i = 0; i < total_strobes; ++i )
988         {
989                 printHex(cur_keymap[i]);
990                 print(" ");
991         }
992 #endif
993
994         ze_strober++;
995         ze_strober &= 0xf;
996
997         dump_count++;
998         dump_count &= 0x0f;
999 }
1000