1 /* Copyright (C) 2011-2013 by Joseph Makuch
2 * Additions by Jacob Alexander (2013)
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>
28 #include "scan_loop.h"
32 // ----- Defines -----
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
39 #define THRESHOLD (THRESHOLD_MV / MV_PER_ADC)
41 #define STROBE_SETTLE 1
43 #define TEST_KEY_STROBE (0x05)
44 #define TEST_KEY_MASK (1 << 0)
48 #define RIGHT_JUSTIFY 0
49 #define LEFT_JUSTIFY (0xff)
51 // set left or right justification here:
52 #define JUSTIFY_ADC RIGHT_JUSTIFY
53 #define ADLAR_MASK (1 << ADLAR)
56 #define ADLAR_BITS ((ADLAR_MASK) & (JUSTIFY_ADC))
57 #else // defaults to right justification.
62 #define FULL_MUX_MASK ((1 << MUX0) | (1 << MUX1) | (1 << MUX2) | (1 << MUX3) | (1 << MUX4))
64 // F0-f7 pins only muxmask.
65 #define MUX_MASK ((1 << MUX0) | (1 << MUX1) | (1 << MUX2))
72 // set ADC clock prescale
73 #define PRESCALE_MASK ((1 << ADPS0) | (1 << ADPS1) | (1 << ADPS2))
74 #define PRESCALE_SHIFT (ADPS0)
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
81 // Number of consecutive samples required to pass debounce
82 #define DEBOUNCE_THRESHOLD 5
85 #define MUXES_COUNT_XSHIFT 3
87 #define WARMUP_LOOPS ( 1024 )
88 #define WARMUP_STOP (WARMUP_LOOPS - 1)
90 #define SAMPLE_CONTROL 3
92 #define KEY_COUNT ((MAX_STROBES) * (MUXES_COUNT))
94 #define RECOVERY_CONTROL 1
95 #define RECOVERY_SOURCE 0
96 #define RECOVERY_SINK 2
101 // mix in 1/4 of the current average to the running average. -> (@mux_mix = 2)
104 #define IDLE_COUNT_MASK 0xff
105 #define IDLE_COUNT_SHIFT 8
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
115 // ----- Macros -----
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
123 #define SET_FULL_MUX(X) ((ADMUX) = (((ADMUX) & ~(FULL_MUX_MASK)) | ((X) & (FULL_MUX_MASK))))
127 // ----- Variables -----
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;
134 // TODO dfj variables...needs cleaning up and commenting
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;
141 uint8_t high_count = 0;
142 uint8_t low_count = 0;
145 uint8_t ze_strober = 0;
147 uint16_t samples[MUXES_COUNT];
149 uint8_t cur_keymap[MAX_STROBES];
151 uint8_t keymap_change;
153 uint16_t threshold = THRESHOLD;
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)
162 uint8_t full_samples[KEY_COUNT];
164 // TODO: change this to 'booting', then count down.
165 uint16_t boot_count = 0;
167 uint16_t idle_count = 0;
171 uint16_t error_data = 0;
173 uint8_t total_strobes = MAX_STROBES;
174 uint8_t strobe_map[MAX_STROBES];
176 uint8_t dump_count = 0;
180 // ----- Function Declarations -----
184 void recovery( uint8_t on );
186 int sampleColumn( uint8_t column );
188 void capsense_scan( void );
190 void setup_ADC( void );
192 void strobe_w( uint8_t strobe_num );
194 uint8_t testColumn( uint8_t strobe );
198 // ----- Functions -----
200 // Initial setup for cap sense controller
201 inline void scan_setup()
203 // TODO dfj code...needs cleanup + commenting...
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
223 strobe_map[0] = 2; // Kishsaver doesn't use strobe 0 and 1
231 strobe_map[8] = 15; // Test point strobe (3 test points, sense 1, 4, 5)
232 #elif defined(KISHSAVER_STROBE)
235 strobe_map[0] = 15; // Kishsaver doesn't use strobe 0 and 1
243 strobe_map[8] = 2; // Test point strobe (3 test points, sense 1, 4, 5)
244 #elif defined(TERMINAL_6110668_OLD_STROBE)
263 #elif defined(UNSAVER_OLD_STROBE)
285 // TODO all this code should probably be in scan_resetKeyboard
286 for ( int i = 0; i < total_strobes; ++i)
291 // Reset debounce table
292 for ( int i = 0; i < KEY_COUNT; ++i )
294 keys_debounce[i] = 0;
297 // Warm things up a bit before we start collecting data, taking real samples.
298 for ( uint8_t i = 0; i < total_strobes; ++i )
300 sampleColumn( strobe_map[i] );
304 // Reset the keyboard before scanning, we might be in a wierd state
305 // Also sets the KeyIndex_BufferUsed to 0
306 scan_resetKeyboard();
310 // Main Detection Loop
311 // This is where the important stuff happens
312 inline uint8_t scan_loop()
316 // Error case, should not occur in normal operation
319 erro_msg("Problem detected... ");
322 for ( uint8_t i = 0; i < total_strobes; ++i )
324 printHex(cur_keymap[strobe_map[i]]);
332 printHex(error_data);
335 // Display keymaps and other debug information if warmup completede
336 if ( boot_count >= WARMUP_LOOPS )
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
352 void scan_resetKeyboard( void )
354 // Empty buffer, now that keyboard has been reset
355 KeyIndex_BufferUsed = 0;
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 )
367 // Reset/Hold keyboard
368 // NOTE: Only used for converters, not needed for full controllers
369 void scan_lockKeyboard( void )
373 // NOTE: Only used for converters, not needed for full controllers
374 void scan_unlockKeyboard( void )
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 )
383 // Convenient place to clear the KeyIndex_Buffer
384 KeyIndex_BufferUsed = 0;
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 )
397 inline void capsense_scan()
399 // Accumulated average used for the next scan
400 uint32_t cur_full_avg = 0;
401 uint32_t cur_high_avg = 0;
403 // Reset average counters
409 // Scan each of the mapped strobes in the matrix
410 for ( uint8_t strober = 0; strober < total_strobes; ++strober )
412 uint8_t map_strobe = strobe_map[strober];
415 while ( tries++ && sampleColumn( map_strobe ) ) { tries &= 0x7; } // don't waste this one just because the last one was poop.
417 // Only process sense data if warmup is finished
418 if ( boot_count >= WARMUP_LOOPS )
420 column = testColumn( map_strobe );
422 idle |= column; // if column has any pressed keys, then we are not idle.
424 // TODO Is this needed anymore? Really only helps debug -HaaTa
425 if( column != cur_keymap[map_strobe] && ( boot_count >= WARMUP_LOOPS ) )
427 cur_keymap[map_strobe] = column;
431 idle |= keymap_change; // if any keys have changed inc. released, then we are not idle.
436 error_data |= (((uint16_t)map_strobe) << 12);
439 uint8_t strobe_line = map_strobe << MUXES_COUNT_XSHIFT;
440 for ( int i = 0; i < MUXES_COUNT; ++i )
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;
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 )
456 for ( uint8_t i = 0; i < MUXES_COUNT; ++i )
458 uint8_t sample = samples[i] >> 1;
460 // Sample is high, add it to high avg
461 if ( sample > full_avg )
464 cur_high_avg += sample;
466 // Sample is low, add it to low avg
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;
476 // Prepare for next average
477 cur_full_avg += sample;
482 // Update total sense average (only during warm-up)
483 if ( boot_count < WARMUP_LOOPS )
485 full_avg = cur_full_avg / (total_strobes * MUXES_COUNT);
486 high_avg = cur_high_avg / high_count;
487 low_avg /= low_count;
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 )
492 keys_averages[i] = low_avg;
493 keys_averages_acc[i] = low_avg;
497 #ifdef VERIFY_TEST_PAD
498 // verify test key is not down.
499 if ( ( cur_keymap[TEST_KEY_STROBE] & TEST_KEY_MASK ) )
502 error_data = cur_keymap[TEST_KEY_STROBE] << 8;
503 error_data += full_samples[TEST_KEY_STROBE * 8];
507 /** aggregate if booting, or if idle;
508 * else, if not booting, check for dirty USB.
512 idle_count &= IDLE_COUNT_MASK;
514 // Warm up voltage references
515 if ( boot_count < WARMUP_LOOPS )
519 switch ( boot_count )
523 // Show msg at first iteration only
524 info_msg("Warming up the voltage references");
536 info_msg("Warmup finished using ");
537 printInt16( WARMUP_LOOPS );
538 print(" iterations\n");
540 // Display the final calculated averages of all the sensed strobes
541 info_msg("Full average (");
542 printInt8( total_strobes * MUXES_COUNT );
544 printHex( full_avg );
546 print(" High average (");
547 printInt8( high_count );
549 printHex( high_avg );
551 print(" Low average (");
552 printInt8( low_count );
557 // Display problem keys, and the sense value at the time
558 for ( uint8_t key = 0; key < KEY_COUNT; key++ )
560 if ( keys_problem[key] )
562 warn_msg("Problem key detected: ");
565 printHex( keys_problem[key] );
570 info_print("If problem keys were detected, and were being held down, they will be reset as soon as let go");
576 // Reset accumulators and idle flag/counter
579 for ( uint8_t c = 0; c < KEY_COUNT; ++c ) { keys_averages_acc[c] = 0; }
591 for ( uint8_t i = 0; i < KEY_COUNT; ++i )
593 uint16_t acc = keys_averages_acc[i] >> IDLE_COUNT_SHIFT;
594 uint32_t av = keys_averages[i];
596 av = (av << KEYS_AVERAGES_MIX_SHIFT) - av + acc;
597 av >>= KEYS_AVERAGES_MIX_SHIFT;
599 keys_averages[i] = av;
600 keys_averages_acc[i] = 0;
604 if ( boot_count >= WARMUP_LOOPS )
616 // disable adc digital pins.
617 DIDR1 |= (1 << AIN0D) | (1<<AIN1D); // set disable on pins 1,0.
620 uint8_t mux = 0 & 0x1f; // 0 == first. // 0x1e = 1.1V ref.
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);
631 ADCSRA = (1 << ADEN) | prescale; // ADC enable
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;
640 ADCSRA |= adate; // trigger enable
641 ADCSRB = en_mux | hispeed | trig | (ADCSRB & ~((1 << ADTS0) | (1 << ADTS1) | (1 << ADTS2))); // trigger select free running
643 ADCSRA |= (1 << ADEN); // ADC enable
644 ADCSRA |= (1 << ADSC); // start conversions q
648 void recovery( uint8_t on )
650 DDRB |= (1 << RECOVERY_CONTROL);
651 PORTB &= ~(1 << RECOVERY_SINK); // SINK always zero
652 DDRB &= ~(1 << RECOVERY_SOURCE); // SOURCE high imp
656 // set strobes to sink to gnd.
665 DDRB |= (1 << RECOVERY_SINK); // SINK pull
666 PORTB |= (1 << RECOVERY_CONTROL);
667 PORTB |= (1 << RECOVERY_SOURCE); // SOURCE high
668 DDRB |= (1 << RECOVERY_SOURCE);
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
680 void hold_sample( uint8_t on )
684 PORTB |= (1 << SAMPLE_CONTROL);
685 DDRB |= (1 << SAMPLE_CONTROL);
689 DDRB |= (1 << SAMPLE_CONTROL);
690 PORTB &= ~(1 << SAMPLE_CONTROL);
695 void strobe_w( uint8_t strobe_num )
702 // Not all strobes are used depending on which are detected
703 switch ( strobe_num )
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;
715 case 8: PORTE |= (1 << 0); break;
716 case 9: PORTE |= (1 << 1); break;
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;
733 inline uint16_t getADC(void)
735 ADCSRA |= (1 << ADIF); // clear int flag by writing 1.
737 //wait for last read to complete.
738 while ( !( ADCSRA & (1 << ADIF) ) );
740 return ADC; // return sample
744 int sampleColumn_8x( uint8_t column, uint16_t * buffer )
746 // ensure all probe lines are driven low, and chill for recovery delay.
747 ADCSRA |= (1 << ADEN) | (1 << ADSC); // enable and start conversions
762 // Allow strobes to settle
763 for ( uint8_t i = 0; i < STROBE_SETTLE; ++i ) { getADC(); }
769 getADC(); // throw away; unknown mux.
771 SET_FULL_MUX( mux + 1 ); // our *next* sample will use this
773 // retrieve current read.
774 buffer[mux] = getADC();
783 ADCSRA &= ~(1 << ADEN);
785 // pull all columns' strobe-lines low.
798 int sampleColumn( uint8_t column )
802 rval = sampleColumn_8x( column, samples );
808 uint8_t testColumn( uint8_t strobe )
810 uint16_t db_delta = 0;
811 uint8_t db_sample = 0;
812 uint16_t db_threshold = 0;
817 for ( uint8_t mux = 0; mux < MUXES_COUNT; ++mux )
819 uint16_t delta = keys_averages[(strobe << MUXES_COUNT_XSHIFT) + mux];
821 uint8_t key = (strobe << MUXES_COUNT_XSHIFT) + mux;
823 // Check if this is a bad key (e.g. test point, or non-existent key)
824 if ( keys_problem[key] )
826 // If the sample value of the problem key goes below full_avg (overall initial average)
828 if ( (db_sample = samples[mux] >> 1) < full_avg )
830 info_msg("Re-enabling problem key: ");
834 keys_problem[key] = 0;
836 // Otherwise, don't waste any more cycles processing the problem key
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) )
849 // Only register keypresses once the warmup is complete, or not enough debounce info
850 if ( keys_debounce[key] <= DEBOUNCE_THRESHOLD )
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 )
856 //#define KEYSCAN_DEBOUNCE_DEBUG
857 #ifdef KEYSCAN_DEBOUNCE_DEBUG
860 printHex_op( key, 2 );
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
870 keys_debounce[key]++;
872 #define KEYSCAN_THRESHOLD_DEBUG
873 #ifdef KEYSCAN_THRESHOLD_DEBUG
875 // <key> [<strobe>:<mux>] : <sense val> : <delta + threshold> : <margin>
877 printHex_op( key, 2 );
883 printHex( db_sample ); // Sense
885 printHex( db_threshold );
887 printHex( db_delta );
889 printHex( db_threshold + db_delta ); // Sense compare
891 printHex( db_sample - ( db_threshold + db_delta ) ); // Margin
896 // Clear debounce entry if no keypress detected
899 // If the key was previously pressed, remove from the buffer
900 for ( uint8_t c = 0; c < KeyIndex_BufferUsed; c++ )
902 // Key to release found
903 if ( KeyIndex_Buffer[c] == key )
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];
910 KeyIndex_BufferUsed--;
917 // Clear debounce entry
918 keys_debounce[key] = 0;
929 #ifdef DEBUG_FULL_SAMPLES_AVERAGES
930 // we don't want to debug-out during the measurements.
933 // Averages currently set per key
934 for ( int i = 0; i < KEY_COUNT; ++i )
940 else if ( !(i & 0x07) )
946 printHex( keys_averages[i] );
951 // Previously read full ADC scans?
952 for ( int i = 0; i< KEY_COUNT; ++i)
958 else if ( !(i & 0x07) )
964 printHex(full_samples[i]);
969 #ifdef DEBUG_STROBE_SAMPLES_AVERAGES
970 // Per strobe information
971 uint8_t cur_strober = ze_strober;
974 printHex(cur_strober);
976 // Previously read ADC scans on current strobe
978 for ( uint8_t i = 0; i < MUXES_COUNT; ++i )
981 printHex(full_samples[(cur_strober << MUXES_COUNT_XSHIFT) + i]);
984 // Averages current set on current strobe
987 for ( uint8_t i = 0; i < MUXES_COUNT; ++i )
990 printHex(keys_averages[(cur_strober << MUXES_COUNT_XSHIFT) + i]);
995 #ifdef DEBUG_USB_KEYMAP
998 // Current keymap values
999 for ( uint8_t i = 0; i < total_strobes; ++i )
1001 printHex(cur_keymap[i]);