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/Disables 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 for ( int i = 0; i < total_strobes; ++i)
319 // Reset debounce table
320 for ( int i = 0; i < KEY_COUNT; ++i )
322 keys_debounce[i] = 0;
325 // Warm things up a bit before we start collecting data, taking real samples.
326 for ( uint8_t i = 0; i < total_strobes; ++i )
328 sampleColumn( strobe_map[i] );
333 // Main Detection Loop
334 // This is where the important stuff happens
335 inline uint8_t Scan_loop()
339 // Error case, should not occur in normal operation
342 erro_msg("Problem detected... ");
345 for ( uint8_t i = 0; i < total_strobes; ++i )
347 printHex(cur_keymap[strobe_map[i]]);
355 printHex(error_data);
358 // Display sense table if warmup completede
359 if ( boot_count >= WARMUP_LOOPS )
366 // Return non-zero if macro and USB processing should be delayed
367 // Macro processing will always run if returning 0
368 // USB processing only happens once the USB send timer expires, if it has not, Scan_loop will be called
369 // after the macro processing has been completed
374 // Signal KeyIndex_Buffer that it has been properly read
375 // NOTE: Only really required for implementing "tricks" in converters for odd protocols
376 void Scan_finishedWithBuffer( uint8_t sentKeys )
378 // Convenient place to clear the KeyIndex_Buffer
379 KeyIndex_BufferUsed = 0;
384 // Signal KeyIndex_Buffer that it has been properly read and sent out by the USB module
385 // NOTE: Only really required for implementing "tricks" in converters for odd protocols
386 void Scan_finishedWithUSBBuffer( uint8_t sentKeys )
392 inline void capsense_scan()
394 // Accumulated average used for the next scan
395 uint32_t cur_full_avg = 0;
396 uint32_t cur_high_avg = 0;
398 // Reset average counters
404 // Scan each of the mapped strobes in the matrix
405 for ( uint8_t strober = 0; strober < total_strobes; ++strober )
407 uint8_t map_strobe = strobe_map[strober];
410 while ( tries++ && sampleColumn( map_strobe ) ) { tries &= 0x7; } // don't waste this one just because the last one was poop.
412 // Only process sense data if warmup is finished
413 if ( boot_count >= WARMUP_LOOPS )
415 column = testColumn( map_strobe );
417 idle |= column; // if column has any pressed keys, then we are not idle.
419 // TODO Is this needed anymore? Really only helps debug -HaaTa
420 if( column != cur_keymap[map_strobe] && ( boot_count >= WARMUP_LOOPS ) )
422 cur_keymap[map_strobe] = column;
426 idle |= keymap_change; // if any keys have changed inc. released, then we are not idle.
431 error_data |= (((uint16_t)map_strobe) << 12);
434 uint8_t strobe_line = map_strobe << MUXES_COUNT_XSHIFT;
435 for ( int mux = 0; mux < MUXES_COUNT; ++mux )
437 // discard sketchy low bit, and meaningless high bits.
438 uint8_t sample = samples[map_strobe][mux] >> 1;
439 full_samples[strobe_line + mux] = sample;
440 keys_averages_acc[strobe_line + mux] += sample;
443 // Accumulate 3 total averages (used for determining starting average during warmup)
444 // full_avg - Average of all sampled lines on the previous scan set
445 // cur_full_avg - Average of all sampled lines for this scan set
446 // high_avg - Average of all sampled lines above full_avg on the previous scan set
447 // cur_high_avg - Average of all sampled lines above full_avg
448 // low_avg - Average of all sampled lines below or equal to full_avg
449 if ( boot_count < WARMUP_LOOPS )
451 for ( uint8_t mux = 0; mux < MUXES_COUNT; ++mux )
453 uint8_t sample = samples[map_strobe][mux] >> 1;
455 // Sample is high, add it to high avg
456 if ( sample > full_avg )
459 cur_high_avg += sample;
461 // Sample is low, add it to low avg
468 // If sample is higher than previous high_avg, then mark as "problem key"
469 keys_problem[strobe_line + mux] = sample > high_avg ? sample : 0;
471 // Prepare for next average
472 cur_full_avg += sample;
477 // Update total sense average (only during warm-up)
478 if ( boot_count < WARMUP_LOOPS )
480 full_avg = cur_full_avg / (total_strobes * MUXES_COUNT);
481 high_avg = cur_high_avg / high_count;
482 low_avg /= low_count;
484 // Update the base average value using the low_avg (best chance of not ignoring a keypress)
485 for ( int i = 0; i < KEY_COUNT; ++i )
487 keys_averages[i] = low_avg;
488 keys_averages_acc[i] = low_avg;
492 #ifdef VERIFY_TEST_PAD
493 // verify test key is not down.
494 if ( ( cur_keymap[TEST_KEY_STROBE] & TEST_KEY_MASK ) )
497 error_data = cur_keymap[TEST_KEY_STROBE] << 8;
498 error_data += full_samples[TEST_KEY_STROBE * 8];
502 /** aggregate if booting, or if idle;
503 * else, if not booting, check for dirty USB.
507 idle_count &= IDLE_COUNT_MASK;
509 // Warm up voltage references
510 if ( boot_count < WARMUP_LOOPS )
514 switch ( boot_count )
518 // Show msg at first iteration only
519 info_msg("Warming up the voltage references");
531 info_msg("Warmup finished using ");
532 printInt16( WARMUP_LOOPS );
533 print(" iterations" NL );
535 // Display the final calculated averages of all the sensed strobes
536 info_msg("Full average (");
537 printInt8( total_strobes * MUXES_COUNT );
539 printHex( full_avg );
541 print(" High average (");
542 printInt8( high_count );
544 printHex( high_avg );
546 print(" Low average (");
547 printInt8( low_count );
552 // Display problem keys, and the sense value at the time
553 for ( uint8_t key = 0; key < KEY_COUNT; key++ )
555 if ( keys_problem[key] )
557 warn_msg("Problem key detected: ");
560 printHex( keys_problem[key] );
565 info_print("If problem keys were detected, and were being held down, they will be reset as soon as let go");
571 // Reset accumulators and idle flag/counter
574 for ( uint8_t c = 0; c < KEY_COUNT; ++c ) { keys_averages_acc[c] = 0; }
586 for ( uint8_t i = 0; i < KEY_COUNT; ++i )
588 uint16_t acc = keys_averages_acc[i] >> IDLE_COUNT_SHIFT;
589 uint32_t av = keys_averages[i];
591 av = (av << KEYS_AVERAGES_MIX_SHIFT) - av + acc;
592 av >>= KEYS_AVERAGES_MIX_SHIFT;
594 keys_averages[i] = av;
595 keys_averages_acc[i] = 0;
599 // If the debugging sense table is non-zero, display
600 if ( senseDebugCount > 0 )
614 // disable adc digital pins.
615 DIDR1 |= (1 << AIN0D) | (1<<AIN1D); // set disable on pins 1,0.
618 uint8_t mux = 0 & 0x1f; // 0 == first. // 0x1e = 1.1V ref.
620 // 0 = external aref 1,1 = 2.56V internal ref
621 uint8_t aref = ((1 << REFS1) | (1 << REFS0)) & ((1 << REFS1) | (1 << REFS0));
622 uint8_t adate = (1 << ADATE) & (1 << ADATE); // trigger enable
623 uint8_t trig = 0 & ((1 << ADTS0) | (1 << ADTS1) | (1 << ADTS2)); // 0 = free running
624 // ps2, ps1 := /64 ( 2^6 ) ps2 := /16 (2^4), ps1 := 4, ps0 :=2, PS1,PS0 := 8 (2^8)
625 uint8_t prescale = ( ((PRESCALE) << PRESCALE_SHIFT) & PRESCALE_MASK ); // 001 == 2^1 == 2
626 uint8_t hispeed = (1 << ADHSM);
627 uint8_t en_mux = (1 << ACME);
629 ADCSRA = (1 << ADEN) | prescale; // ADC enable
632 //ADMUX |= ((1 << REFS1) | (1 << REFS0)); // 2.56 V internal.
633 //ADMUX |= ((1 << REFS0) ); // Vcc with external cap.
634 //ADMUX &= ~((1 << REFS1) | (1 << REFS0)); // 0,0 : aref.
635 ADMUX = aref | mux | ADLAR_BITS;
638 ADCSRA |= adate; // trigger enable
639 ADCSRB = en_mux | hispeed | trig | (ADCSRB & ~((1 << ADTS0) | (1 << ADTS1) | (1 << ADTS2))); // trigger select free running
641 ADCSRA |= (1 << ADEN); // ADC enable
642 ADCSRA |= (1 << ADSC); // start conversions q
646 void recovery( uint8_t on )
648 DDRB |= (1 << RECOVERY_CONTROL);
649 PORTB &= ~(1 << RECOVERY_SINK); // SINK always zero
650 DDRB &= ~(1 << RECOVERY_SOURCE); // SOURCE high imp
654 // set strobes to sink to gnd.
663 DDRB |= (1 << RECOVERY_SINK); // SINK pull
664 PORTB |= (1 << RECOVERY_CONTROL);
665 PORTB |= (1 << RECOVERY_SOURCE); // SOURCE high
666 DDRB |= (1 << RECOVERY_SOURCE);
670 PORTB &= ~(1 << RECOVERY_CONTROL);
671 DDRB &= ~(1 << RECOVERY_SOURCE);
672 PORTB &= ~(1 << RECOVERY_SOURCE); // SOURCE low
673 DDRB &= ~(1 << RECOVERY_SINK); // SINK high-imp
678 void hold_sample( uint8_t on )
682 PORTB |= (1 << SAMPLE_CONTROL);
683 DDRB |= (1 << SAMPLE_CONTROL);
687 DDRB |= (1 << SAMPLE_CONTROL);
688 PORTB &= ~(1 << SAMPLE_CONTROL);
693 void strobe_w( uint8_t strobe_num )
700 // Not all strobes are used depending on which are detected
701 switch ( strobe_num )
704 case 0: PORTD |= (1 << 0); break;
705 case 1: PORTD |= (1 << 1); break;
706 case 2: PORTD |= (1 << 2); break;
707 case 3: PORTD |= (1 << 3); break;
708 case 4: PORTD |= (1 << 4); break;
709 case 5: PORTD |= (1 << 5); break;
710 case 6: PORTD |= (1 << 6); break;
711 case 7: PORTD |= (1 << 7); break;
713 case 8: PORTE |= (1 << 0); break;
714 case 9: PORTE |= (1 << 1); break;
716 case 10: PORTC |= (1 << 0); break;
717 case 11: PORTC |= (1 << 1); break;
718 case 12: PORTC |= (1 << 2); break;
719 case 13: PORTC |= (1 << 3); break;
720 case 14: PORTC |= (1 << 4); break;
721 case 15: PORTC |= (1 << 5); break;
722 case 16: PORTC |= (1 << 6); break;
723 case 17: PORTC |= (1 << 7); break;
731 inline uint16_t getADC(void)
733 ADCSRA |= (1 << ADIF); // clear int flag by writing 1.
735 //wait for last read to complete.
736 while ( !( ADCSRA & (1 << ADIF) ) );
738 return ADC; // return sample
742 int sampleColumn( uint8_t column )
744 // ensure all probe lines are driven low, and chill for recovery delay.
745 ADCSRA |= (1 << ADEN) | (1 << ADSC); // enable and start conversions
760 // Allow strobes to settle
761 for ( uint8_t i = 0; i < STROBE_SETTLE; ++i ) { getADC(); }
767 getADC(); // throw away; unknown mux.
769 SET_FULL_MUX( mux + 1 ); // our *next* sample will use this
771 // retrieve current read.
772 samples[column][mux] = getADC();
781 ADCSRA &= ~(1 << ADEN);
783 // pull all columns' strobe-lines low.
796 uint8_t testColumn( uint8_t strobe )
798 uint16_t db_delta = 0;
799 uint8_t db_sample = 0;
800 uint16_t db_threshold = 0;
805 for ( uint8_t mux = 0; mux < MUXES_COUNT; ++mux )
807 uint16_t delta = keys_averages[(strobe << MUXES_COUNT_XSHIFT) + mux];
809 uint8_t key = (strobe << MUXES_COUNT_XSHIFT) + mux;
811 // Check if this is a bad key (e.g. test point, or non-existent key)
812 if ( keys_problem[key] )
814 // If the sample value of the problem key goes below full_avg (overall initial average)
816 if ( (db_sample = samples[strobe][mux] >> 1) < full_avg )
818 info_msg("Re-enabling problem key: ");
822 keys_problem[key] = 0;
824 // Otherwise, don't waste any more cycles processing the problem key
832 // db_sample (uint8_t), discard meaningless high bit, and garbage low bit
833 if ( (db_sample = samples[strobe][mux] >> 1) > (db_threshold = threshold) + (db_delta = delta) )
837 // Only register keypresses once the warmup is complete, or not enough debounce info
838 if ( keys_debounce[key] <= DEBOUNCE_THRESHOLD )
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 )
844 //#define KEYSCAN_DEBOUNCE_DEBUG
845 #ifdef KEYSCAN_DEBOUNCE_DEBUG
848 printHex_op( key, 2 );
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 //Macro_bufferAdd( key );
858 keys_debounce[key]++;
860 // Long form key debugging
861 if ( enableKeyDebug )
864 // <key> [<strobe>:<mux>] : <sense val> : <delta + threshold> : <margin>
866 printHex_op( key, 2 );
872 printHex( db_sample ); // Sense
874 printHex( db_threshold );
876 printHex( db_delta );
878 printHex( db_threshold + db_delta ); // Sense compare
880 printHex( db_sample - ( db_threshold + db_delta ) ); // Margin
885 // Clear debounce entry if no keypress detected
888 // If the key was previously pressed, remove from the buffer
889 for ( uint8_t c = 0; c < KeyIndex_BufferUsed; c++ )
891 // Key to release found
892 if ( KeyIndex_Buffer[c] == key )
894 // Shift keys from c position
895 for ( uint8_t k = c; k < KeyIndex_BufferUsed - 1; k++ )
896 KeyIndex_Buffer[k] = KeyIndex_Buffer[k + 1];
899 KeyIndex_BufferUsed--;
906 // Clear debounce entry
907 keys_debounce[key] = 0;
916 void dumpSenseTable()
918 // Initial table alignment
921 // Print out headers first
922 for ( uint8_t mux = 0; mux < MUXES_COUNT; ++mux )
924 print(" Mux \033[1m");
931 // Display the full strobe/sense table
932 for ( uint8_t strober = 0; strober < total_strobes; ++strober )
934 uint8_t strobe = strobe_map[strober];
936 // Display the strobe
937 print("Strobe \033[1m");
941 // For each mux, display sense:threshold:delta
942 for ( uint8_t mux = 0; mux < MUXES_COUNT; ++mux )
944 uint8_t delta = keys_averages[(strobe << MUXES_COUNT_XSHIFT) + mux];
945 uint8_t sample = samples[strobe][mux] >> 1; // TODO Make larger samples array (2d)
947 printHex_op( sample, 2 );
949 printHex_op( threshold, 2 );
951 printHex_op( delta, 2 );
955 // New line for each strobe
961 // ----- CLI Command Functions -----
963 // XXX Just an example command showing how to parse arguments (more complex than generally needed)
964 void cliFunc_echo( char* args )
968 char* arg2Ptr = args;
970 // Parse args until a \0 is found
973 print( NL ); // No \r\n by default after the command is entered
975 curArgs = arg2Ptr; // Use the previous 2nd arg pointer to separate the next arg from the list
976 CLI_argumentIsolation( curArgs, &arg1Ptr, &arg2Ptr );
978 // Stop processing args if no more are found
979 if ( *arg1Ptr == '\0' )
987 void cliFunc_keyDebug( char* args )
991 // Args ignored, just toggling
992 if ( enableKeyDebug )
994 info_print("Cap Sense key debug disabled.");
999 info_print("Cap Sense key debug enabled.");
1004 void cliFunc_senseDebug( char* args )
1006 // Parse code from argument
1007 // NOTE: Only first argument is used
1010 CLI_argumentIsolation( args, &arg1Ptr, &arg2Ptr );
1012 // Default to a single print
1013 senseDebugCount = 1;
1015 // If there was an argument, use that instead
1016 if ( *arg1Ptr != '\0' )
1018 senseDebugCount = decToInt( arg1Ptr );