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>
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 -----
118 #define SET_FULL_MUX(X) ((ADMUX) = (((ADMUX) & ~(FULL_MUX_MASK)) | ((X) & (FULL_MUX_MASK))))
122 // ----- Variables -----
124 // Buffer used to inform the macro processing module which keys have been detected as pressed
125 volatile uint8_t KeyIndex_Buffer[KEYBOARD_BUFFER];
126 volatile uint8_t KeyIndex_BufferUsed;
129 // TODO dfj variables...needs cleaning up and commenting
131 // Variables used to calculate the starting sense value (averaging)
132 uint32_t full_avg = 0;
133 uint32_t high_avg = 0;
134 uint32_t low_avg = 0;
136 uint8_t high_count = 0;
137 uint8_t low_count = 0;
140 uint8_t ze_strober = 0;
142 uint16_t samples[MUXES_COUNT];
144 uint8_t cur_keymap[MAX_STROBES];
146 uint8_t keymap_change;
148 uint16_t threshold = THRESHOLD;
152 uint16_t keys_averages_acc[KEY_COUNT];
153 uint16_t keys_averages [KEY_COUNT];
154 uint8_t keys_debounce [KEY_COUNT]; // Contains debounce statistics
155 uint8_t keys_problem [KEY_COUNT]; // Marks keys that should be ignored (determined by averaging at startup)
157 uint8_t full_samples[KEY_COUNT];
159 // TODO: change this to 'booting', then count down.
160 uint16_t boot_count = 0;
162 uint16_t idle_count = 0;
166 uint16_t error_data = 0;
168 uint8_t total_strobes = MAX_STROBES;
169 uint8_t strobe_map[MAX_STROBES];
171 uint8_t dump_count = 0;
175 // ----- Function Declarations -----
179 void recovery( uint8_t on );
181 int sampleColumn( uint8_t column );
183 void capsense_scan( void );
185 void setup_ADC( void );
187 void strobe_w( uint8_t strobe_num );
189 uint8_t testColumn( uint8_t strobe );
193 // ----- Functions -----
195 // Initial setup for cap sense controller
196 inline void Scan_setup()
198 // TODO dfj code...needs cleanup + commenting...
208 // Hardcoded strobes for debugging
209 // Strobes start at 0 and go to 17 (18), not all Model Fs use all of the available strobes
210 // The single row ribbon connector Model Fs only have a max of 16 strobes
211 #define KISHSAVER_STROBE
212 //#define KISHSAVER_OLD_STROBE
213 //#define TERMINAL_6110668_OLD_STROBE
214 //#define UNSAVER_OLD_STROBE
215 #ifdef KISHSAVER_OLD_STROBE
218 strobe_map[0] = 2; // Kishsaver doesn't use strobe 0 and 1
226 strobe_map[8] = 15; // Test point strobe (3 test points, sense 1, 4, 5)
227 #elif defined(KISHSAVER_STROBE)
230 strobe_map[0] = 15; // Kishsaver doesn't use strobe 0 and 1
238 strobe_map[8] = 2; // Test point strobe (3 test points, sense 1, 4, 5)
239 #elif defined(TERMINAL_6110668_OLD_STROBE)
258 #elif defined(UNSAVER_OLD_STROBE)
280 // TODO all this code should probably be in Scan_resetKeyboard
281 for ( int i = 0; i < total_strobes; ++i)
286 // Reset debounce table
287 for ( int i = 0; i < KEY_COUNT; ++i )
289 keys_debounce[i] = 0;
292 // Warm things up a bit before we start collecting data, taking real samples.
293 for ( uint8_t i = 0; i < total_strobes; ++i )
295 sampleColumn( strobe_map[i] );
299 // Reset the keyboard before scanning, we might be in a wierd state
300 // Also sets the KeyIndex_BufferUsed to 0
301 scan_resetKeyboard();
305 // Main Detection Loop
306 // This is where the important stuff happens
307 inline uint8_t Scan_loop()
311 // Error case, should not occur in normal operation
314 erro_msg("Problem detected... ");
317 for ( uint8_t i = 0; i < total_strobes; ++i )
319 printHex(cur_keymap[strobe_map[i]]);
327 printHex(error_data);
330 // Display keymaps and other debug information if warmup completede
331 if ( boot_count >= WARMUP_LOOPS )
338 // Return non-zero if macro and USB processing should be delayed
339 // Macro processing will always run if returning 0
340 // USB processing only happens once the USB send timer expires, if it has not, Scan_loop will be called
341 // after the macro processing has been completed
346 // Signal KeyIndex_Buffer that it has been properly read
347 // NOTE: Only really required for implementing "tricks" in converters for odd protocols
348 void Scan_finishedWithBuffer( uint8_t sentKeys )
350 // Convenient place to clear the KeyIndex_Buffer
351 KeyIndex_BufferUsed = 0;
356 // Signal KeyIndex_Buffer that it has been properly read and sent out by the USB module
357 // NOTE: Only really required for implementing "tricks" in converters for odd protocols
358 void Scan_finishedWithUSBBuffer( uint8_t sentKeys )
364 inline void capsense_scan()
366 // Accumulated average used for the next scan
367 uint32_t cur_full_avg = 0;
368 uint32_t cur_high_avg = 0;
370 // Reset average counters
376 // Scan each of the mapped strobes in the matrix
377 for ( uint8_t strober = 0; strober < total_strobes; ++strober )
379 uint8_t map_strobe = strobe_map[strober];
382 while ( tries++ && sampleColumn( map_strobe ) ) { tries &= 0x7; } // don't waste this one just because the last one was poop.
384 // Only process sense data if warmup is finished
385 if ( boot_count >= WARMUP_LOOPS )
387 column = testColumn( map_strobe );
389 idle |= column; // if column has any pressed keys, then we are not idle.
391 // TODO Is this needed anymore? Really only helps debug -HaaTa
392 if( column != cur_keymap[map_strobe] && ( boot_count >= WARMUP_LOOPS ) )
394 cur_keymap[map_strobe] = column;
398 idle |= keymap_change; // if any keys have changed inc. released, then we are not idle.
403 error_data |= (((uint16_t)map_strobe) << 12);
406 uint8_t strobe_line = map_strobe << MUXES_COUNT_XSHIFT;
407 for ( int i = 0; i < MUXES_COUNT; ++i )
409 // discard sketchy low bit, and meaningless high bits.
410 uint8_t sample = samples[i] >> 1;
411 full_samples[strobe_line + i] = sample;
412 keys_averages_acc[strobe_line + i] += sample;
415 // Accumulate 3 total averages (used for determining starting average during warmup)
416 // full_avg - Average of all sampled lines on the previous scan set
417 // cur_full_avg - Average of all sampled lines for this scan set
418 // high_avg - Average of all sampled lines above full_avg on the previous scan set
419 // cur_high_avg - Average of all sampled lines above full_avg
420 // low_avg - Average of all sampled lines below or equal to full_avg
421 if ( boot_count < WARMUP_LOOPS )
423 for ( uint8_t i = 0; i < MUXES_COUNT; ++i )
425 uint8_t sample = samples[i] >> 1;
427 // Sample is high, add it to high avg
428 if ( sample > full_avg )
431 cur_high_avg += sample;
433 // Sample is low, add it to low avg
440 // If sample is higher than previous high_avg, then mark as "problem key"
441 keys_problem[strobe_line + i] = sample > high_avg ? sample : 0;
443 // Prepare for next average
444 cur_full_avg += sample;
449 // Update total sense average (only during warm-up)
450 if ( boot_count < WARMUP_LOOPS )
452 full_avg = cur_full_avg / (total_strobes * MUXES_COUNT);
453 high_avg = cur_high_avg / high_count;
454 low_avg /= low_count;
456 // Update the base average value using the low_avg (best chance of not ignoring a keypress)
457 for ( int i = 0; i < KEY_COUNT; ++i )
459 keys_averages[i] = low_avg;
460 keys_averages_acc[i] = low_avg;
464 #ifdef VERIFY_TEST_PAD
465 // verify test key is not down.
466 if ( ( cur_keymap[TEST_KEY_STROBE] & TEST_KEY_MASK ) )
469 error_data = cur_keymap[TEST_KEY_STROBE] << 8;
470 error_data += full_samples[TEST_KEY_STROBE * 8];
474 /** aggregate if booting, or if idle;
475 * else, if not booting, check for dirty USB.
479 idle_count &= IDLE_COUNT_MASK;
481 // Warm up voltage references
482 if ( boot_count < WARMUP_LOOPS )
486 switch ( boot_count )
490 // Show msg at first iteration only
491 info_msg("Warming up the voltage references");
503 info_msg("Warmup finished using ");
504 printInt16( WARMUP_LOOPS );
505 print(" iterations\n");
507 // Display the final calculated averages of all the sensed strobes
508 info_msg("Full average (");
509 printInt8( total_strobes * MUXES_COUNT );
511 printHex( full_avg );
513 print(" High average (");
514 printInt8( high_count );
516 printHex( high_avg );
518 print(" Low average (");
519 printInt8( low_count );
524 // Display problem keys, and the sense value at the time
525 for ( uint8_t key = 0; key < KEY_COUNT; key++ )
527 if ( keys_problem[key] )
529 warn_msg("Problem key detected: ");
532 printHex( keys_problem[key] );
537 info_print("If problem keys were detected, and were being held down, they will be reset as soon as let go");
543 // Reset accumulators and idle flag/counter
546 for ( uint8_t c = 0; c < KEY_COUNT; ++c ) { keys_averages_acc[c] = 0; }
558 for ( uint8_t i = 0; i < KEY_COUNT; ++i )
560 uint16_t acc = keys_averages_acc[i] >> IDLE_COUNT_SHIFT;
561 uint32_t av = keys_averages[i];
563 av = (av << KEYS_AVERAGES_MIX_SHIFT) - av + acc;
564 av >>= KEYS_AVERAGES_MIX_SHIFT;
566 keys_averages[i] = av;
567 keys_averages_acc[i] = 0;
571 if ( boot_count >= WARMUP_LOOPS )
583 // disable adc digital pins.
584 DIDR1 |= (1 << AIN0D) | (1<<AIN1D); // set disable on pins 1,0.
587 uint8_t mux = 0 & 0x1f; // 0 == first. // 0x1e = 1.1V ref.
589 // 0 = external aref 1,1 = 2.56V internal ref
590 uint8_t aref = ((1 << REFS1) | (1 << REFS0)) & ((1 << REFS1) | (1 << REFS0));
591 uint8_t adate = (1 << ADATE) & (1 << ADATE); // trigger enable
592 uint8_t trig = 0 & ((1 << ADTS0) | (1 << ADTS1) | (1 << ADTS2)); // 0 = free running
593 // ps2, ps1 := /64 ( 2^6 ) ps2 := /16 (2^4), ps1 := 4, ps0 :=2, PS1,PS0 := 8 (2^8)
594 uint8_t prescale = ( ((PRESCALE) << PRESCALE_SHIFT) & PRESCALE_MASK ); // 001 == 2^1 == 2
595 uint8_t hispeed = (1 << ADHSM);
596 uint8_t en_mux = (1 << ACME);
598 ADCSRA = (1 << ADEN) | prescale; // ADC enable
601 //ADMUX |= ((1 << REFS1) | (1 << REFS0)); // 2.56 V internal.
602 //ADMUX |= ((1 << REFS0) ); // Vcc with external cap.
603 //ADMUX &= ~((1 << REFS1) | (1 << REFS0)); // 0,0 : aref.
604 ADMUX = aref | mux | ADLAR_BITS;
607 ADCSRA |= adate; // trigger enable
608 ADCSRB = en_mux | hispeed | trig | (ADCSRB & ~((1 << ADTS0) | (1 << ADTS1) | (1 << ADTS2))); // trigger select free running
610 ADCSRA |= (1 << ADEN); // ADC enable
611 ADCSRA |= (1 << ADSC); // start conversions q
615 void recovery( uint8_t on )
617 DDRB |= (1 << RECOVERY_CONTROL);
618 PORTB &= ~(1 << RECOVERY_SINK); // SINK always zero
619 DDRB &= ~(1 << RECOVERY_SOURCE); // SOURCE high imp
623 // set strobes to sink to gnd.
632 DDRB |= (1 << RECOVERY_SINK); // SINK pull
633 PORTB |= (1 << RECOVERY_CONTROL);
634 PORTB |= (1 << RECOVERY_SOURCE); // SOURCE high
635 DDRB |= (1 << RECOVERY_SOURCE);
639 PORTB &= ~(1 << RECOVERY_CONTROL);
640 DDRB &= ~(1 << RECOVERY_SOURCE);
641 PORTB &= ~(1 << RECOVERY_SOURCE); // SOURCE low
642 DDRB &= ~(1 << RECOVERY_SINK); // SINK high-imp
647 void hold_sample( uint8_t on )
651 PORTB |= (1 << SAMPLE_CONTROL);
652 DDRB |= (1 << SAMPLE_CONTROL);
656 DDRB |= (1 << SAMPLE_CONTROL);
657 PORTB &= ~(1 << SAMPLE_CONTROL);
662 void strobe_w( uint8_t strobe_num )
669 // Not all strobes are used depending on which are detected
670 switch ( strobe_num )
673 case 0: PORTD |= (1 << 0); break;
674 case 1: PORTD |= (1 << 1); break;
675 case 2: PORTD |= (1 << 2); break;
676 case 3: PORTD |= (1 << 3); break;
677 case 4: PORTD |= (1 << 4); break;
678 case 5: PORTD |= (1 << 5); break;
679 case 6: PORTD |= (1 << 6); break;
680 case 7: PORTD |= (1 << 7); break;
682 case 8: PORTE |= (1 << 0); break;
683 case 9: PORTE |= (1 << 1); break;
685 case 10: PORTC |= (1 << 0); break;
686 case 11: PORTC |= (1 << 1); break;
687 case 12: PORTC |= (1 << 2); break;
688 case 13: PORTC |= (1 << 3); break;
689 case 14: PORTC |= (1 << 4); break;
690 case 15: PORTC |= (1 << 5); break;
691 case 16: PORTC |= (1 << 6); break;
692 case 17: PORTC |= (1 << 7); break;
700 inline uint16_t getADC(void)
702 ADCSRA |= (1 << ADIF); // clear int flag by writing 1.
704 //wait for last read to complete.
705 while ( !( ADCSRA & (1 << ADIF) ) );
707 return ADC; // return sample
711 int sampleColumn_8x( uint8_t column, uint16_t * buffer )
713 // ensure all probe lines are driven low, and chill for recovery delay.
714 ADCSRA |= (1 << ADEN) | (1 << ADSC); // enable and start conversions
729 // Allow strobes to settle
730 for ( uint8_t i = 0; i < STROBE_SETTLE; ++i ) { getADC(); }
736 getADC(); // throw away; unknown mux.
738 SET_FULL_MUX( mux + 1 ); // our *next* sample will use this
740 // retrieve current read.
741 buffer[mux] = getADC();
750 ADCSRA &= ~(1 << ADEN);
752 // pull all columns' strobe-lines low.
765 int sampleColumn( uint8_t column )
769 rval = sampleColumn_8x( column, samples );
775 uint8_t testColumn( uint8_t strobe )
777 uint16_t db_delta = 0;
778 uint8_t db_sample = 0;
779 uint16_t db_threshold = 0;
784 for ( uint8_t mux = 0; mux < MUXES_COUNT; ++mux )
786 uint16_t delta = keys_averages[(strobe << MUXES_COUNT_XSHIFT) + mux];
788 uint8_t key = (strobe << MUXES_COUNT_XSHIFT) + mux;
790 // Check if this is a bad key (e.g. test point, or non-existent key)
791 if ( keys_problem[key] )
793 // If the sample value of the problem key goes below full_avg (overall initial average)
795 if ( (db_sample = samples[mux] >> 1) < full_avg )
797 info_msg("Re-enabling problem key: ");
801 keys_problem[key] = 0;
803 // Otherwise, don't waste any more cycles processing the problem key
811 // db_sample (uint8_t), discard meaningless high bit, and garbage low bit
812 if ( (db_sample = samples[mux] >> 1) > (db_threshold = threshold) + (db_delta = delta) )
816 // Only register keypresses once the warmup is complete, or not enough debounce info
817 if ( keys_debounce[key] <= DEBOUNCE_THRESHOLD )
819 // Add to the Macro processing buffer if debounce criteria met
820 // Automatically handles converting to a USB code and sending off to the PC
821 if ( keys_debounce[key] == DEBOUNCE_THRESHOLD )
823 //#define KEYSCAN_DEBOUNCE_DEBUG
824 #ifdef KEYSCAN_DEBOUNCE_DEBUG
827 printHex_op( key, 2 );
831 // Only add the key to the buffer once
832 // NOTE: Buffer can easily handle multiple adds, just more efficient
833 // and nicer debug messages :P
834 //Macro_bufferAdd( key );
837 keys_debounce[key]++;
839 #define KEYSCAN_THRESHOLD_DEBUG
840 #ifdef KEYSCAN_THRESHOLD_DEBUG
842 // <key> [<strobe>:<mux>] : <sense val> : <delta + threshold> : <margin>
844 printHex_op( key, 2 );
850 printHex( db_sample ); // Sense
852 printHex( db_threshold );
854 printHex( db_delta );
856 printHex( db_threshold + db_delta ); // Sense compare
858 printHex( db_sample - ( db_threshold + db_delta ) ); // Margin
863 // Clear debounce entry if no keypress detected
866 // If the key was previously pressed, remove from the buffer
867 for ( uint8_t c = 0; c < KeyIndex_BufferUsed; c++ )
869 // Key to release found
870 if ( KeyIndex_Buffer[c] == key )
872 // Shift keys from c position
873 for ( uint8_t k = c; k < KeyIndex_BufferUsed - 1; k++ )
874 KeyIndex_Buffer[k] = KeyIndex_Buffer[k + 1];
877 KeyIndex_BufferUsed--;
884 // Clear debounce entry
885 keys_debounce[key] = 0;
896 #ifdef DEBUG_FULL_SAMPLES_AVERAGES
897 // we don't want to debug-out during the measurements.
900 // Averages currently set per key
901 for ( int i = 0; i < KEY_COUNT; ++i )
907 else if ( !(i & 0x07) )
913 printHex( keys_averages[i] );
918 // Previously read full ADC scans?
919 for ( int i = 0; i< KEY_COUNT; ++i)
925 else if ( !(i & 0x07) )
931 printHex(full_samples[i]);
936 #ifdef DEBUG_STROBE_SAMPLES_AVERAGES
937 // Per strobe information
938 uint8_t cur_strober = ze_strober;
941 printHex(cur_strober);
943 // Previously read ADC scans on current strobe
945 for ( uint8_t i = 0; i < MUXES_COUNT; ++i )
948 printHex(full_samples[(cur_strober << MUXES_COUNT_XSHIFT) + i]);
951 // Averages current set on current strobe
954 for ( uint8_t i = 0; i < MUXES_COUNT; ++i )
957 printHex(keys_averages[(cur_strober << MUXES_COUNT_XSHIFT) + i]);
962 #ifdef DEBUG_USB_KEYMAP
965 // Current keymap values
966 for ( uint8_t i = 0; i < total_strobes; ++i )
968 printHex(cur_keymap[i]);