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 TERMINAL_6110668_STROBE
218 //#define UNSAVER_STROBE
219 #ifdef KISHSAVER_STROBE
222 strobe_map[0] = 2; // Kishsaver doesn't use strobe 0 and 1
230 // XXX - Disabling for now, not sure how to deal with test points yet (without spamming the debug)
232 strobe_map[8] = 15; // Test point strobe (3 test points, sense 1, 4, 5)
233 #elif defined(TERMINAL_6110668_STROBE)
252 #elif defined(UNSAVER_STROBE)
274 // TODO all this code should probably be in scan_resetKeyboard
275 for ( int i = 0; i < total_strobes; ++i)
280 // Reset debounce table
281 for ( int i = 0; i < KEY_COUNT; ++i )
283 keys_debounce[i] = 0;
286 // Warm things up a bit before we start collecting data, taking real samples.
287 for ( uint8_t i = 0; i < total_strobes; ++i )
289 sampleColumn( strobe_map[i] );
293 // Reset the keyboard before scanning, we might be in a wierd state
294 // Also sets the KeyIndex_BufferUsed to 0
295 scan_resetKeyboard();
299 // Main Detection Loop
300 // This is where the important stuff happens
301 inline uint8_t scan_loop()
305 // Error case, should not occur in normal operation
308 erro_msg("Problem detected... ");
311 for ( uint8_t i = 0; i < total_strobes; ++i )
313 printHex(cur_keymap[strobe_map[i]]);
321 printHex(error_data);
324 // Display keymaps and other debug information if warmup completede
325 if ( boot_count >= WARMUP_LOOPS )
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
341 void scan_resetKeyboard( void )
343 // Empty buffer, now that keyboard has been reset
344 KeyIndex_BufferUsed = 0;
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 )
356 // Reset/Hold keyboard
357 // NOTE: Only used for converters, not needed for full controllers
358 void scan_lockKeyboard( void )
362 // NOTE: Only used for converters, not needed for full controllers
363 void scan_unlockKeyboard( void )
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 )
372 // Convenient place to clear the KeyIndex_Buffer
373 KeyIndex_BufferUsed = 0;
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 )
386 inline void capsense_scan()
388 // Accumulated average used for the next scan
389 uint32_t cur_full_avg = 0;
390 uint32_t cur_high_avg = 0;
392 // Reset average counters
398 // Scan each of the mapped strobes in the matrix
399 for ( uint8_t strober = 0; strober < total_strobes; ++strober )
401 uint8_t map_strobe = strobe_map[strober];
404 while ( tries++ && sampleColumn( map_strobe ) ) { tries &= 0x7; } // don't waste this one just because the last one was poop.
406 // Only process sense data if warmup is finished
407 if ( boot_count >= WARMUP_LOOPS )
409 column = testColumn( map_strobe );
411 idle |= column; // if column has any pressed keys, then we are not idle.
413 // TODO Is this needed anymore? Really only helps debug -HaaTa
414 if( column != cur_keymap[map_strobe] && ( boot_count >= WARMUP_LOOPS ) )
416 cur_keymap[map_strobe] = column;
420 idle |= keymap_change; // if any keys have changed inc. released, then we are not idle.
425 error_data |= (((uint16_t)map_strobe) << 12);
428 uint8_t strobe_line = map_strobe << MUXES_COUNT_XSHIFT;
429 for ( int i = 0; i < MUXES_COUNT; ++i )
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;
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 )
445 for ( uint8_t i = 0; i < MUXES_COUNT; ++i )
447 uint8_t sample = samples[i] >> 1;
449 // Sample is high, add it to high avg
450 if ( sample > full_avg )
453 cur_high_avg += sample;
455 // Sample is low, add it to low avg
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;
465 // Prepare for next average
466 cur_full_avg += sample;
471 // Update total sense average (only during warm-up)
472 if ( boot_count < WARMUP_LOOPS )
474 full_avg = cur_full_avg / (total_strobes * MUXES_COUNT);
475 high_avg = cur_high_avg / high_count;
476 low_avg /= low_count;
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 )
481 keys_averages[i] = low_avg;
482 keys_averages_acc[i] = low_avg;
486 #ifdef VERIFY_TEST_PAD
487 // verify test key is not down.
488 if ( ( cur_keymap[TEST_KEY_STROBE] & TEST_KEY_MASK ) )
491 error_data = cur_keymap[TEST_KEY_STROBE] << 8;
492 error_data += full_samples[TEST_KEY_STROBE * 8];
496 /** aggregate if booting, or if idle;
497 * else, if not booting, check for dirty USB.
501 idle_count &= IDLE_COUNT_MASK;
503 // Warm up voltage references
504 if ( boot_count < WARMUP_LOOPS )
508 switch ( boot_count )
512 // Show msg at first iteration only
513 info_msg("Warming up the voltage references");
525 info_msg("Warmup finished using ");
526 printInt16( WARMUP_LOOPS );
527 print(" iterations\n");
529 // Display the final calculated averages of all the sensed strobes
530 info_msg("Full average (");
531 printInt8( total_strobes * MUXES_COUNT );
533 printHex( full_avg );
535 print(" High average (");
536 printInt8( high_count );
538 printHex( high_avg );
540 print(" Low average (");
541 printInt8( low_count );
546 // Display problem keys, and the sense value at the time
547 for ( uint8_t key = 0; key < KEY_COUNT; key++ )
549 if ( keys_problem[key] )
551 warn_msg("Problem key detected: ");
554 printHex( keys_problem[key] );
559 info_print("If problem keys were detected, and were being held down, they will be reset as soon as let go");
565 // Reset accumulators and idle flag/counter
568 for ( uint8_t c = 0; c < KEY_COUNT; ++c ) { keys_averages_acc[c] = 0; }
580 for ( uint8_t i = 0; i < KEY_COUNT; ++i )
582 uint16_t acc = keys_averages_acc[i] >> IDLE_COUNT_SHIFT;
583 uint32_t av = keys_averages[i];
585 av = (av << KEYS_AVERAGES_MIX_SHIFT) - av + acc;
586 av >>= KEYS_AVERAGES_MIX_SHIFT;
588 keys_averages[i] = av;
589 keys_averages_acc[i] = 0;
593 if ( boot_count >= WARMUP_LOOPS )
605 // disable adc digital pins.
606 DIDR1 |= (1 << AIN0D) | (1<<AIN1D); // set disable on pins 1,0.
609 uint8_t mux = 0 & 0x1f; // 0 == first. // 0x1e = 1.1V ref.
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);
620 ADCSRA = (1 << ADEN) | prescale; // ADC enable
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;
629 ADCSRA |= adate; // trigger enable
630 ADCSRB = en_mux | hispeed | trig | (ADCSRB & ~((1 << ADTS0) | (1 << ADTS1) | (1 << ADTS2))); // trigger select free running
632 ADCSRA |= (1 << ADEN); // ADC enable
633 ADCSRA |= (1 << ADSC); // start conversions q
637 void recovery( uint8_t on )
639 DDRB |= (1 << RECOVERY_CONTROL);
640 PORTB &= ~(1 << RECOVERY_SINK); // SINK always zero
641 DDRB &= ~(1 << RECOVERY_SOURCE); // SOURCE high imp
645 // set strobes to sink to gnd.
654 DDRB |= (1 << RECOVERY_SINK); // SINK pull
655 PORTB |= (1 << RECOVERY_CONTROL);
656 PORTB |= (1 << RECOVERY_SOURCE); // SOURCE high
657 DDRB |= (1 << RECOVERY_SOURCE);
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
669 void hold_sample( uint8_t on )
673 PORTB |= (1 << SAMPLE_CONTROL);
674 DDRB |= (1 << SAMPLE_CONTROL);
678 DDRB |= (1 << SAMPLE_CONTROL);
679 PORTB &= ~(1 << SAMPLE_CONTROL);
684 void strobe_w( uint8_t strobe_num )
691 // Not all strobes are used depending on which are detected
692 switch ( strobe_num )
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;
704 case 8: PORTE |= (1 << 0); break;
705 case 9: PORTE |= (1 << 1); break;
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;
722 inline uint16_t getADC(void)
724 ADCSRA |= (1 << ADIF); // clear int flag by writing 1.
726 //wait for last read to complete.
727 while ( !( ADCSRA & (1 << ADIF) ) );
729 return ADC; // return sample
733 int sampleColumn_8x( uint8_t column, uint16_t * buffer )
735 // ensure all probe lines are driven low, and chill for recovery delay.
736 ADCSRA |= (1 << ADEN) | (1 << ADSC); // enable and start conversions
751 for ( uint8_t i = 0; i < STROBE_SETTLE; ++i ) { getADC(); }
757 getADC(); // throw away; unknown mux.
759 SET_FULL_MUX(mux + 1); // our *next* sample will use this
761 // retrieve current read.
762 buffer[mux] = getADC();
771 ADCSRA &= ~(1 << ADEN);
773 // pull all columns' strobe-lines low.
786 int sampleColumn( uint8_t column )
790 rval = sampleColumn_8x( column, samples );
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[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[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
858 keys_debounce[key]++;
860 #define KEYSCAN_THRESHOLD_DEBUG
861 #ifdef KEYSCAN_THRESHOLD_DEBUG
863 // <key> [<strobe>:<mux>] : <sense val> : <delta + threshold> : <margin>
865 printHex_op( key, 2 );
871 printHex( db_sample ); // Sense
873 printHex( db_threshold );
875 printHex( db_delta );
877 printHex( db_threshold + db_delta ); // Sense compare
879 printHex( db_sample - ( db_threshold + db_delta ) ); // Margin
884 // Clear debounce entry if no keypress detected
887 // If the key was previously pressed, remove from the buffer
888 for ( uint8_t c = 0; c < KeyIndex_BufferUsed; c++ )
890 // Key to release found
891 if ( KeyIndex_Buffer[c] == key )
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];
898 KeyIndex_BufferUsed--;
905 // Clear debounce entry
906 keys_debounce[key] = 0;
917 #ifdef DEBUG_FULL_SAMPLES_AVERAGES
918 // we don't want to debug-out during the measurements.
921 // Averages currently set per key
922 for ( int i = 0; i < KEY_COUNT; ++i )
928 else if ( !(i & 0x07) )
934 printHex( keys_averages[i] );
939 // Previously read full ADC scans?
940 for ( int i = 0; i< KEY_COUNT; ++i)
946 else if ( !(i & 0x07) )
952 printHex(full_samples[i]);
957 #ifdef DEBUG_STROBE_SAMPLES_AVERAGES
958 // Per strobe information
959 uint8_t cur_strober = ze_strober;
962 printHex(cur_strober);
964 // Previously read ADC scans on current strobe
966 for ( uint8_t i = 0; i < MUXES_COUNT; ++i )
969 printHex(full_samples[(cur_strober << MUXES_COUNT_XSHIFT) + i]);
972 // Averages current set on current strobe
975 for ( uint8_t i = 0; i < MUXES_COUNT; ++i )
978 printHex(keys_averages[(cur_strober << MUXES_COUNT_XSHIFT) + i]);
983 #ifdef DEBUG_USB_KEYMAP
986 // Current keymap values
987 for ( uint8_t i = 0; i < total_strobes; ++i )
989 printHex(cur_keymap[i]);