1 /* Copyright (C) 2011-2013 by Joseph Makuch
2 * Additions by Jacob Alexander (2013-2014)
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.
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.
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/>.
18 // ----- Includes -----
21 #include <Lib/ScanLib.h>
29 #include "scan_loop.h"
33 // ----- Defines -----
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
40 #define THRESHOLD (THRESHOLD_MV / MV_PER_ADC)
42 #define STROBE_SETTLE 1
44 #define TEST_KEY_STROBE (0x05)
45 #define TEST_KEY_MASK (1 << 0)
49 #define RIGHT_JUSTIFY 0
50 #define LEFT_JUSTIFY (0xff)
52 // set left or right justification here:
53 #define JUSTIFY_ADC RIGHT_JUSTIFY
54 #define ADLAR_MASK (1 << ADLAR)
57 #define ADLAR_BITS ((ADLAR_MASK) & (JUSTIFY_ADC))
58 #else // defaults to right justification.
63 #define FULL_MUX_MASK ((1 << MUX0) | (1 << MUX1) | (1 << MUX2) | (1 << MUX3) | (1 << MUX4))
65 // F0-f7 pins only muxmask.
66 #define MUX_MASK ((1 << MUX0) | (1 << MUX1) | (1 << MUX2))
73 // set ADC clock prescale
74 #define PRESCALE_MASK ((1 << ADPS0) | (1 << ADPS1) | (1 << ADPS2))
75 #define PRESCALE_SHIFT (ADPS0)
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
82 // Number of consecutive samples required to pass debounce
83 #define DEBOUNCE_THRESHOLD 5
86 #define MUXES_COUNT_XSHIFT 3
88 #define WARMUP_LOOPS ( 1024 )
89 #define WARMUP_STOP (WARMUP_LOOPS - 1)
91 #define SAMPLE_CONTROL 3
93 #define KEY_COUNT ((MAX_STROBES) * (MUXES_COUNT))
95 #define RECOVERY_CONTROL 1
96 #define RECOVERY_SOURCE 0
97 #define RECOVERY_SINK 2
102 // mix in 1/4 of the current average to the running average. -> (@mux_mix = 2)
105 #define IDLE_COUNT_MASK 0xff
106 #define IDLE_COUNT_SHIFT 8
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
116 // ----- Macros -----
119 #define SET_FULL_MUX(X) ((ADMUX) = (((ADMUX) & ~(FULL_MUX_MASK)) | ((X) & (FULL_MUX_MASK))))
123 // ----- Function Declarations -----
125 void cliFunc_echo ( char* args );
126 void cliFunc_keyDebug ( char* args );
127 void cliFunc_senseDebug( char* args );
131 // ----- Variables -----
133 // Buffer used to inform the macro processing module which keys have been detected as pressed
134 volatile uint8_t KeyIndex_Buffer[KEYBOARD_BUFFER];
135 volatile uint8_t KeyIndex_BufferUsed;
138 // Scan Module command dictionary
139 char* scanCLIDictName = "DPH Module Commands";
140 CLIDictItem scanCLIDict[] = {
141 { "echo", "Example command, echos the arguments.", cliFunc_echo },
142 { "keyDebug", "Enables long debug for each keypress." NL "\t\tkeycode - [strobe:mux] : sense val : threshold+delta=total : margin", cliFunc_keyDebug },
143 { "senseDebug", "Prints out the current sense table N times." NL "\t\tsense:threshold:delta.", cliFunc_senseDebug },
144 { 0, 0, 0 } // Null entry for dictionary end
147 // CLI Control Variables
148 uint8_t enableKeyDebug = 1; // XXX Debugging on by default for now -HaaTa
149 uint8_t senseDebugCount = 0;
152 // TODO dfj variables...needs cleaning up and commenting
154 // Variables used to calculate the starting sense value (averaging)
155 uint32_t full_avg = 0;
156 uint32_t high_avg = 0;
157 uint32_t low_avg = 0;
159 uint8_t high_count = 0;
160 uint8_t low_count = 0;
163 uint16_t samples[MAX_STROBES][MUXES_COUNT];
165 uint8_t cur_keymap[MAX_STROBES];
167 uint8_t keymap_change;
169 uint16_t threshold = THRESHOLD;
173 uint16_t keys_averages_acc[KEY_COUNT];
174 uint16_t keys_averages [KEY_COUNT];
175 uint8_t keys_debounce [KEY_COUNT]; // Contains debounce statistics
176 uint8_t keys_problem [KEY_COUNT]; // Marks keys that should be ignored (determined by averaging at startup)
178 uint8_t full_samples[KEY_COUNT];
180 // TODO: change this to 'booting', then count down.
181 uint16_t boot_count = 0;
183 uint16_t idle_count = 0;
187 uint16_t error_data = 0;
189 uint8_t total_strobes = MAX_STROBES;
190 uint8_t strobe_map[MAX_STROBES];
194 // ----- Function Declarations -----
196 void dumpSenseTable();
198 void recovery( uint8_t on );
200 int sampleColumn( uint8_t column );
202 void capsense_scan();
206 void strobe_w( uint8_t strobe_num );
208 uint8_t testColumn( uint8_t strobe );
212 // ----- Functions -----
214 // Initial setup for cap sense controller
215 inline void Scan_setup()
217 // Register Scan CLI dictionary
218 CLI_registerDictionary( scanCLIDict, scanCLIDictName );
220 // TODO dfj code...needs cleanup + commenting...
230 // Hardcoded strobes for debugging
231 // Strobes start at 0 and go to 17 (18), not all Model Fs use all of the available strobes
232 // The single row ribbon connector Model Fs only have a max of 16 strobes
234 //#define KISHSAVER_STROBE
235 //#define KISHSAVER_OLD_STROBE
236 //#define TERMINAL_6110668_OLD_STROBE
237 //#define UNSAVER_OLD_STROBE
238 #ifdef KISHSAVER_OLD_STROBE
241 strobe_map[0] = 2; // Kishsaver doesn't use strobe 0 and 1
249 strobe_map[8] = 15; // Test point strobe (3 test points, sense 1, 4, 5)
250 #elif defined(KISHSAVER_STROBE)
253 strobe_map[0] = 15; // Kishsaver doesn't use strobe 0 and 1
261 strobe_map[8] = 2; // Test point strobe (3 test points, sense 1, 4, 5)
262 #elif defined(KEYPAD_50KEY)
273 #elif defined(TERMINAL_6110668_OLD_STROBE)
292 #elif defined(UNSAVER_OLD_STROBE)
314 // TODO all this code should probably be in Scan_resetKeyboard
315 for ( int i = 0; i < total_strobes; ++i)
320 // Reset debounce table
321 for ( int i = 0; i < KEY_COUNT; ++i )
323 keys_debounce[i] = 0;
326 // Warm things up a bit before we start collecting data, taking real samples.
327 for ( uint8_t i = 0; i < total_strobes; ++i )
329 sampleColumn( strobe_map[i] );
334 // Main Detection Loop
335 // This is where the important stuff happens
336 inline uint8_t Scan_loop()
340 // Error case, should not occur in normal operation
343 erro_msg("Problem detected... ");
346 for ( uint8_t i = 0; i < total_strobes; ++i )
348 printHex(cur_keymap[strobe_map[i]]);
356 printHex(error_data);
359 // Display sense table if warmup completede
360 if ( boot_count >= WARMUP_LOOPS )
367 // Return non-zero if macro and USB processing should be delayed
368 // Macro processing will always run if returning 0
369 // USB processing only happens once the USB send timer expires, if it has not, Scan_loop will be called
370 // after the macro processing has been completed
375 // Signal KeyIndex_Buffer that it has been properly read
376 // NOTE: Only really required for implementing "tricks" in converters for odd protocols
377 void Scan_finishedWithBuffer( uint8_t sentKeys )
379 // Convenient place to clear the KeyIndex_Buffer
380 KeyIndex_BufferUsed = 0;
385 // Signal KeyIndex_Buffer that it has been properly read and sent out by the USB module
386 // NOTE: Only really required for implementing "tricks" in converters for odd protocols
387 void Scan_finishedWithUSBBuffer( uint8_t sentKeys )
393 inline void capsense_scan()
395 // Accumulated average used for the next scan
396 uint32_t cur_full_avg = 0;
397 uint32_t cur_high_avg = 0;
399 // Reset average counters
405 // Scan each of the mapped strobes in the matrix
406 for ( uint8_t strober = 0; strober < total_strobes; ++strober )
408 uint8_t map_strobe = strobe_map[strober];
411 while ( tries++ && sampleColumn( map_strobe ) ) { tries &= 0x7; } // don't waste this one just because the last one was poop.
413 // Only process sense data if warmup is finished
414 if ( boot_count >= WARMUP_LOOPS )
416 column = testColumn( map_strobe );
418 idle |= column; // if column has any pressed keys, then we are not idle.
420 // TODO Is this needed anymore? Really only helps debug -HaaTa
421 if( column != cur_keymap[map_strobe] && ( boot_count >= WARMUP_LOOPS ) )
423 cur_keymap[map_strobe] = column;
427 idle |= keymap_change; // if any keys have changed inc. released, then we are not idle.
432 error_data |= (((uint16_t)map_strobe) << 12);
435 uint8_t strobe_line = map_strobe << MUXES_COUNT_XSHIFT;
436 for ( int mux = 0; mux < MUXES_COUNT; ++mux )
438 // discard sketchy low bit, and meaningless high bits.
439 uint8_t sample = samples[map_strobe][mux] >> 1;
440 full_samples[strobe_line + mux] = sample;
441 keys_averages_acc[strobe_line + mux] += sample;
444 // Accumulate 3 total averages (used for determining starting average during warmup)
445 // full_avg - Average of all sampled lines on the previous scan set
446 // cur_full_avg - Average of all sampled lines for this scan set
447 // high_avg - Average of all sampled lines above full_avg on the previous scan set
448 // cur_high_avg - Average of all sampled lines above full_avg
449 // low_avg - Average of all sampled lines below or equal to full_avg
450 if ( boot_count < WARMUP_LOOPS )
452 for ( uint8_t mux = 0; mux < MUXES_COUNT; ++mux )
454 uint8_t sample = samples[map_strobe][mux] >> 1;
456 // Sample is high, add it to high avg
457 if ( sample > full_avg )
460 cur_high_avg += sample;
462 // Sample is low, add it to low avg
469 // If sample is higher than previous high_avg, then mark as "problem key"
470 keys_problem[strobe_line + mux] = sample > high_avg ? sample : 0;
472 // Prepare for next average
473 cur_full_avg += sample;
478 // Update total sense average (only during warm-up)
479 if ( boot_count < WARMUP_LOOPS )
481 full_avg = cur_full_avg / (total_strobes * MUXES_COUNT);
482 high_avg = cur_high_avg / high_count;
483 low_avg /= low_count;
485 // Update the base average value using the low_avg (best chance of not ignoring a keypress)
486 for ( int i = 0; i < KEY_COUNT; ++i )
488 keys_averages[i] = low_avg;
489 keys_averages_acc[i] = low_avg;
493 #ifdef VERIFY_TEST_PAD
494 // verify test key is not down.
495 if ( ( cur_keymap[TEST_KEY_STROBE] & TEST_KEY_MASK ) )
498 error_data = cur_keymap[TEST_KEY_STROBE] << 8;
499 error_data += full_samples[TEST_KEY_STROBE * 8];
503 /** aggregate if booting, or if idle;
504 * else, if not booting, check for dirty USB.
508 idle_count &= IDLE_COUNT_MASK;
510 // Warm up voltage references
511 if ( boot_count < WARMUP_LOOPS )
515 switch ( boot_count )
519 // Show msg at first iteration only
520 info_msg("Warming up the voltage references");
532 info_msg("Warmup finished using ");
533 printInt16( WARMUP_LOOPS );
534 print(" iterations" NL );
536 // Display the final calculated averages of all the sensed strobes
537 info_msg("Full average (");
538 printInt8( total_strobes * MUXES_COUNT );
540 printHex( full_avg );
542 print(" High average (");
543 printInt8( high_count );
545 printHex( high_avg );
547 print(" Low average (");
548 printInt8( low_count );
553 // Display problem keys, and the sense value at the time
554 for ( uint8_t key = 0; key < KEY_COUNT; key++ )
556 if ( keys_problem[key] )
558 warn_msg("Problem key detected: ");
561 printHex( keys_problem[key] );
566 info_print("If problem keys were detected, and were being held down, they will be reset as soon as let go");
572 // Reset accumulators and idle flag/counter
575 for ( uint8_t c = 0; c < KEY_COUNT; ++c ) { keys_averages_acc[c] = 0; }
587 for ( uint8_t i = 0; i < KEY_COUNT; ++i )
589 uint16_t acc = keys_averages_acc[i] >> IDLE_COUNT_SHIFT;
590 uint32_t av = keys_averages[i];
592 av = (av << KEYS_AVERAGES_MIX_SHIFT) - av + acc;
593 av >>= KEYS_AVERAGES_MIX_SHIFT;
595 keys_averages[i] = av;
596 keys_averages_acc[i] = 0;
600 // If the debugging sense table is non-zero, display
601 if ( senseDebugCount > 0 )
615 // disable adc digital pins.
616 DIDR1 |= (1 << AIN0D) | (1<<AIN1D); // set disable on pins 1,0.
619 uint8_t mux = 0 & 0x1f; // 0 == first. // 0x1e = 1.1V ref.
621 // 0 = external aref 1,1 = 2.56V internal ref
622 uint8_t aref = ((1 << REFS1) | (1 << REFS0)) & ((1 << REFS1) | (1 << REFS0));
623 uint8_t adate = (1 << ADATE) & (1 << ADATE); // trigger enable
624 uint8_t trig = 0 & ((1 << ADTS0) | (1 << ADTS1) | (1 << ADTS2)); // 0 = free running
625 // ps2, ps1 := /64 ( 2^6 ) ps2 := /16 (2^4), ps1 := 4, ps0 :=2, PS1,PS0 := 8 (2^8)
626 uint8_t prescale = ( ((PRESCALE) << PRESCALE_SHIFT) & PRESCALE_MASK ); // 001 == 2^1 == 2
627 uint8_t hispeed = (1 << ADHSM);
628 uint8_t en_mux = (1 << ACME);
630 ADCSRA = (1 << ADEN) | prescale; // ADC enable
633 //ADMUX |= ((1 << REFS1) | (1 << REFS0)); // 2.56 V internal.
634 //ADMUX |= ((1 << REFS0) ); // Vcc with external cap.
635 //ADMUX &= ~((1 << REFS1) | (1 << REFS0)); // 0,0 : aref.
636 ADMUX = aref | mux | ADLAR_BITS;
639 ADCSRA |= adate; // trigger enable
640 ADCSRB = en_mux | hispeed | trig | (ADCSRB & ~((1 << ADTS0) | (1 << ADTS1) | (1 << ADTS2))); // trigger select free running
642 ADCSRA |= (1 << ADEN); // ADC enable
643 ADCSRA |= (1 << ADSC); // start conversions q
647 void recovery( uint8_t on )
649 DDRB |= (1 << RECOVERY_CONTROL);
650 PORTB &= ~(1 << RECOVERY_SINK); // SINK always zero
651 DDRB &= ~(1 << RECOVERY_SOURCE); // SOURCE high imp
655 // set strobes to sink to gnd.
664 DDRB |= (1 << RECOVERY_SINK); // SINK pull
665 PORTB |= (1 << RECOVERY_CONTROL);
666 PORTB |= (1 << RECOVERY_SOURCE); // SOURCE high
667 DDRB |= (1 << RECOVERY_SOURCE);
671 PORTB &= ~(1 << RECOVERY_CONTROL);
672 DDRB &= ~(1 << RECOVERY_SOURCE);
673 PORTB &= ~(1 << RECOVERY_SOURCE); // SOURCE low
674 DDRB &= ~(1 << RECOVERY_SINK); // SINK high-imp
679 void hold_sample( uint8_t on )
683 PORTB |= (1 << SAMPLE_CONTROL);
684 DDRB |= (1 << SAMPLE_CONTROL);
688 DDRB |= (1 << SAMPLE_CONTROL);
689 PORTB &= ~(1 << SAMPLE_CONTROL);
694 void strobe_w( uint8_t strobe_num )
701 // Not all strobes are used depending on which are detected
702 switch ( strobe_num )
705 case 0: PORTD |= (1 << 0); break;
706 case 1: PORTD |= (1 << 1); break;
707 case 2: PORTD |= (1 << 2); break;
708 case 3: PORTD |= (1 << 3); break;
709 case 4: PORTD |= (1 << 4); break;
710 case 5: PORTD |= (1 << 5); break;
711 case 6: PORTD |= (1 << 6); break;
712 case 7: PORTD |= (1 << 7); break;
714 case 8: PORTE |= (1 << 0); break;
715 case 9: PORTE |= (1 << 1); break;
717 case 10: PORTC |= (1 << 0); break;
718 case 11: PORTC |= (1 << 1); break;
719 case 12: PORTC |= (1 << 2); break;
720 case 13: PORTC |= (1 << 3); break;
721 case 14: PORTC |= (1 << 4); break;
722 case 15: PORTC |= (1 << 5); break;
723 case 16: PORTC |= (1 << 6); break;
724 case 17: PORTC |= (1 << 7); break;
732 inline uint16_t getADC(void)
734 ADCSRA |= (1 << ADIF); // clear int flag by writing 1.
736 //wait for last read to complete.
737 while ( !( ADCSRA & (1 << ADIF) ) );
739 return ADC; // return sample
743 int sampleColumn( uint8_t column )
745 // ensure all probe lines are driven low, and chill for recovery delay.
746 ADCSRA |= (1 << ADEN) | (1 << ADSC); // enable and start conversions
761 // Allow strobes to settle
762 for ( uint8_t i = 0; i < STROBE_SETTLE; ++i ) { getADC(); }
768 getADC(); // throw away; unknown mux.
770 SET_FULL_MUX( mux + 1 ); // our *next* sample will use this
772 // retrieve current read.
773 samples[column][mux] = getADC();
782 ADCSRA &= ~(1 << ADEN);
784 // pull all columns' strobe-lines low.
797 uint8_t testColumn( uint8_t strobe )
799 uint16_t db_delta = 0;
800 uint8_t db_sample = 0;
801 uint16_t db_threshold = 0;
806 for ( uint8_t mux = 0; mux < MUXES_COUNT; ++mux )
808 uint16_t delta = keys_averages[(strobe << MUXES_COUNT_XSHIFT) + mux];
810 uint8_t key = (strobe << MUXES_COUNT_XSHIFT) + mux;
812 // Check if this is a bad key (e.g. test point, or non-existent key)
813 if ( keys_problem[key] )
815 // If the sample value of the problem key goes below full_avg (overall initial average)
817 if ( (db_sample = samples[strobe][mux] >> 1) < full_avg )
819 info_msg("Re-enabling problem key: ");
823 keys_problem[key] = 0;
825 // Otherwise, don't waste any more cycles processing the problem key
833 // db_sample (uint8_t), discard meaningless high bit, and garbage low bit
834 if ( (db_sample = samples[strobe][mux] >> 1) > (db_threshold = threshold) + (db_delta = delta) )
838 // Only register keypresses once the warmup is complete, or not enough debounce info
839 if ( keys_debounce[key] <= DEBOUNCE_THRESHOLD )
841 // Add to the Macro processing buffer if debounce criteria met
842 // Automatically handles converting to a USB code and sending off to the PC
843 if ( keys_debounce[key] == DEBOUNCE_THRESHOLD )
845 //#define KEYSCAN_DEBOUNCE_DEBUG
846 #ifdef KEYSCAN_DEBOUNCE_DEBUG
849 printHex_op( key, 2 );
853 // Only add the key to the buffer once
854 // NOTE: Buffer can easily handle multiple adds, just more efficient
855 // and nicer debug messages :P
856 //Macro_bufferAdd( key );
859 keys_debounce[key]++;
861 // Long form key debugging
862 if ( enableKeyDebug )
865 // <key> [<strobe>:<mux>] : <sense val> : <delta + threshold> : <margin>
867 printHex_op( key, 2 );
873 printHex( db_sample ); // Sense
875 printHex( db_threshold );
877 printHex( db_delta );
879 printHex( db_threshold + db_delta ); // Sense compare
881 printHex( db_sample - ( db_threshold + db_delta ) ); // Margin
886 // Clear debounce entry if no keypress detected
889 // If the key was previously pressed, remove from the buffer
890 for ( uint8_t c = 0; c < KeyIndex_BufferUsed; c++ )
892 // Key to release found
893 if ( KeyIndex_Buffer[c] == key )
895 // Shift keys from c position
896 for ( uint8_t k = c; k < KeyIndex_BufferUsed - 1; k++ )
897 KeyIndex_Buffer[k] = KeyIndex_Buffer[k + 1];
900 KeyIndex_BufferUsed--;
907 // Clear debounce entry
908 keys_debounce[key] = 0;
917 void dumpSenseTable()
919 // Display the full strobe/sense table
920 for ( uint8_t strober = 0; strober < total_strobes; ++strober )
922 uint8_t strobe = strobe_map[strober];
924 // For each mux, display sense:threshold:delta
925 for ( uint8_t mux = 0; mux < MUXES_COUNT; ++mux )
927 uint8_t delta = keys_averages[(strobe << MUXES_COUNT_XSHIFT) + mux];
928 uint8_t sample = samples[strobe][mux] >> 1; // TODO Make larger samples array (2d)
930 printHex_op( sample, 2 );
932 printHex_op( threshold, 2 );
934 printHex_op( delta, 2 );
938 // New line for each strobe
944 // ----- CLI Command Functions -----
946 // XXX Just an example command showing how to parse arguments (more complex than generally needed)
947 void cliFunc_echo( char* args )
951 char* arg2Ptr = args;
953 // Parse args until a \0 is found
956 print( NL ); // No \r\n by default after the command is entered
958 curArgs = arg2Ptr; // Use the previous 2nd arg pointer to separate the next arg from the list
959 CLI_argumentIsolation( curArgs, &arg1Ptr, &arg2Ptr );
961 // Stop processing args if no more are found
962 if ( *arg1Ptr == '\0' )
970 void cliFunc_keyDebug( char* args )
972 // Args ignored, just toggling
973 enableKeyDebug = enableKeyDebug ? 0 : 1;
976 void cliFunc_senseDebug( char* args )
978 // Parse code from argument
979 // NOTE: Only first argument is used
982 CLI_argumentIsolation( args, &arg1Ptr, &arg2Ptr );
984 // Default to a single print
987 // If there was an argument, use that instead
988 if ( *arg1Ptr != '\0' )
990 senseDebugCount = decToInt( arg1Ptr );