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 380
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
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)
92 #define SAMPLE_OFFSET ((SAMPLES) - MUXES_COUNT)
93 #define SAMPLE_CONTROL 3
95 // Starting average for keys, per key will adjust during runtime
96 // XXX - A better method is needed to choose this value (i.e. not experimental)
97 // The ideal average is not always found for weak keys if this is set too high...
98 #define DEFAULT_KEY_BASE 0xB0
100 #define KEY_COUNT ((MAX_STROBES) * (MUXES_COUNT))
102 #define RECOVERY_CONTROL 1
103 #define RECOVERY_SOURCE 0
104 #define RECOVERY_SINK 2
109 // mix in 1/4 of the current average to the running average. -> (@mux_mix = 2)
112 #define IDLE_COUNT_MASK 0xff
113 #define IDLE_COUNT_SHIFT 8
115 // av = (av << shift) - av + sample; av >>= shift
116 // e.g. 1 -> (av + sample) / 2 simple average of new and old
117 // 2 -> (3 * av + sample) / 4 i.e. 3:1 mix of old to new.
118 // 3 -> (7 * av + sample) / 8 i.e. 7:1 mix of old to new.
119 #define KEYS_AVERAGES_MIX_SHIFT 3
123 // ----- Macros -----
125 // Make sure we haven't overflowed the buffer
126 #define bufferAdd(byte) \
127 if ( KeyIndex_BufferUsed < KEYBOARD_BUFFER ) \
128 KeyIndex_Buffer[KeyIndex_BufferUsed++] = byte
131 #define SET_FULL_MUX(X) ((ADMUX) = (((ADMUX) & ~(FULL_MUX_MASK)) | ((X) & (FULL_MUX_MASK))))
135 // ----- Variables -----
137 // Buffer used to inform the macro processing module which keys have been detected as pressed
138 volatile uint8_t KeyIndex_Buffer[KEYBOARD_BUFFER];
139 volatile uint8_t KeyIndex_BufferUsed;
142 // TODO dfj variables...needs cleaning up and commenting
143 volatile uint16_t full_av = 0;
145 uint8_t ze_strober = 0;
147 uint16_t samples [SAMPLES];
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];
161 uint8_t full_samples[KEY_COUNT];
163 // TODO: change this to 'booting', then count down.
164 uint16_t boot_count = 0;
166 uint16_t idle_count = 0;
170 uint16_t error_data = 0;
172 uint8_t total_strobes = MAX_STROBES;
173 uint8_t strobe_map[MAX_STROBES];
175 uint8_t dump_count = 0;
177 uint16_t db_delta = 0;
178 uint8_t db_sample = 0;
179 uint16_t db_threshold = 0;
183 // ----- Function Declarations -----
187 void recovery( uint8_t on );
189 int sampleColumn( uint8_t column );
191 void capsense_scan( void );
193 void setup_ADC( void );
195 void strobe_w( uint8_t strobe_num );
197 uint8_t testColumn( uint8_t strobe );
201 // ----- Functions -----
203 // Initial setup for cap sense controller
204 inline void scan_setup()
206 // TODO dfj code...needs cleanup + commenting...
216 // Hardcoded strobes for debugging
217 // Strobes start at 0 and go to 17 (18), not all Model Fs use all of the available strobes
218 // The single row ribbon connector Model Fs only have a max of 16 strobes
219 #define KISHSAVER_STROBE
220 //#define TERMINAL_6110668_STROBE
221 //#define UNSAVER_STROBE
222 #ifdef KISHSAVER_STROBE
226 strobe_map[0] = 2; // Kishsaver doesn't use strobe 0 and 1
234 // XXX - Disabling for now, not sure how to deal with test points yet (without spamming the debug)
235 //strobe_map[9] = 15; // Test point strobe (3 test points, sense 1, 4, 5)
236 #elif defined(TERMINAL_6110668_STROBE)
255 #elif defined(UNSAVER_STROBE)
277 // TODO all this code should probably be in scan_resetKeyboard
278 for ( int i = 0; i < total_strobes; ++i)
283 for ( int i = 0; i < KEY_COUNT; ++i )
285 keys_averages[i] = DEFAULT_KEY_BASE;
286 keys_averages_acc[i] = (DEFAULT_KEY_BASE);
288 // Reset debounce table
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
347 void scan_resetKeyboard( void )
349 // Empty buffer, now that keyboard has been reset
350 KeyIndex_BufferUsed = 0;
354 // Send data to keyboard
355 // NOTE: Only used for converters, since the scan module shouldn't handle sending data in a controller
356 uint8_t scan_sendData( uint8_t dataPayload )
362 // Reset/Hold keyboard
363 // NOTE: Only used for converters, not needed for full controllers
364 void scan_lockKeyboard( void )
368 // NOTE: Only used for converters, not needed for full controllers
369 void scan_unlockKeyboard( void )
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 // TODO dfj code...needs commenting + cleanup...
395 uint32_t full_av_acc = 0;
397 for ( uint8_t strober = 0; strober < total_strobes; ++strober )
399 uint8_t map_strobe = strobe_map[strober];
402 while ( tries++ && sampleColumn( map_strobe ) ) { tries &= 0x7; } // don't waste this one just because the last one was poop.
403 column = testColumn( map_strobe );
405 idle |= column; // if column has any pressed keys, then we are not idle.
407 // TODO Is this needed anymore? Really only helps debug -HaaTa
408 if( column != cur_keymap[map_strobe] && ( boot_count >= WARMUP_LOOPS ) )
410 cur_keymap[map_strobe] = column;
414 idle |= keymap_change; // if any keys have changed inc. released, then we are not idle.
418 error_data |= (((uint16_t)map_strobe) << 12);
421 uint8_t strobe_line = map_strobe << MUXES_COUNT_XSHIFT;
422 for ( int i = 0; i < MUXES_COUNT; ++i )
424 // discard sketchy low bit, and meaningless high bits.
425 uint8_t sample = samples[SAMPLE_OFFSET + i] >> 1;
426 full_samples[strobe_line + i] = sample;
427 keys_averages_acc[strobe_line + i] += sample;
430 for ( uint8_t i = SAMPLE_OFFSET; i < ( SAMPLE_OFFSET + MUXES_COUNT ); ++i )
432 full_av_acc += (samples[i]);
436 #ifdef VERIFY_TEST_PAD
437 // verify test key is not down.
438 if ( ( cur_keymap[TEST_KEY_STROBE] & TEST_KEY_MASK ) )
441 error_data = cur_keymap[TEST_KEY_STROBE] << 8;
442 error_data += full_samples[TEST_KEY_STROBE * 8];
446 /** aggregate if booting, or if idle;
447 * else, if not booting, check for dirty USB.
451 idle_count &= IDLE_COUNT_MASK;
453 // Warm up voltage references
454 if ( boot_count < WARMUP_LOOPS )
458 switch ( boot_count )
462 // Show msg at first iteration only
463 info_msg("Warming up the voltage references");
475 info_msg("Warmup finished using ");
476 printInt16( WARMUP_LOOPS );
477 print(" iterations\n");
483 // Reset accumulators and idle flag/counter
486 for ( uint8_t c = 0; c < KEY_COUNT; ++c ) { keys_averages_acc[c] = 0; }
498 for ( uint8_t i = 0; i < KEY_COUNT; ++i )
500 uint16_t acc = keys_averages_acc[i] >> IDLE_COUNT_SHIFT;
501 uint32_t av = keys_averages[i];
503 av = (av << KEYS_AVERAGES_MIX_SHIFT) - av + acc;
504 av >>= KEYS_AVERAGES_MIX_SHIFT;
506 keys_averages[i] = av;
507 keys_averages_acc[i] = 0;
511 if ( boot_count >= WARMUP_LOOPS )
523 // disable adc digital pins.
524 DIDR1 |= (1 << AIN0D) | (1<<AIN1D); // set disable on pins 1,0.
527 uint8_t mux = 0 & 0x1f; // 0 == first. // 0x1e = 1.1V ref.
529 // 0 = external aref 1,1 = 2.56V internal ref
530 uint8_t aref = ((1 << REFS1) | (1 << REFS0)) & ((1 << REFS1) | (1 << REFS0));
531 uint8_t adate = (1 << ADATE) & (1 << ADATE); // trigger enable
532 uint8_t trig = 0 & ((1 << ADTS0) | (1 << ADTS1) | (1 << ADTS2)); // 0 = free running
533 // ps2, ps1 := /64 ( 2^6 ) ps2 := /16 (2^4), ps1 := 4, ps0 :=2, PS1,PS0 := 8 (2^8)
534 uint8_t prescale = ( ((PRESCALE) << PRESCALE_SHIFT) & PRESCALE_MASK ); // 001 == 2^1 == 2
535 uint8_t hispeed = (1 << ADHSM);
536 uint8_t en_mux = (1 << ACME);
538 ADCSRA = (1 << ADEN) | prescale; // ADC enable
541 //ADMUX |= ((1 << REFS1) | (1 << REFS0)); // 2.56 V internal.
542 //ADMUX |= ((1 << REFS0) ); // Vcc with external cap.
543 //ADMUX &= ~((1 << REFS1) | (1 << REFS0)); // 0,0 : aref.
544 ADMUX = aref | mux | ADLAR_BITS;
547 ADCSRA |= adate; // trigger enable
548 ADCSRB = en_mux | hispeed | trig | (ADCSRB & ~((1 << ADTS0) | (1 << ADTS1) | (1 << ADTS2))); // trigger select free running
550 ADCSRA |= (1 << ADEN); // ADC enable
551 ADCSRA |= (1 << ADSC); // start conversions q
555 void recovery( uint8_t on )
557 DDRB |= (1 << RECOVERY_CONTROL);
558 PORTB &= ~(1 << RECOVERY_SINK); // SINK always zero
559 DDRB &= ~(1 << RECOVERY_SOURCE); // SOURCE high imp
563 // set strobes to sink to gnd.
572 DDRB |= (1 << RECOVERY_SINK); // SINK pull
573 PORTB |= (1 << RECOVERY_CONTROL);
574 PORTB |= (1 << RECOVERY_SOURCE); // SOURCE high
575 DDRB |= (1 << RECOVERY_SOURCE);
579 PORTB &= ~(1 << RECOVERY_CONTROL);
580 DDRB &= ~(1 << RECOVERY_SOURCE);
581 PORTB &= ~(1 << RECOVERY_SOURCE); // SOURCE low
582 DDRB &= ~(1 << RECOVERY_SINK); // SINK high-imp
587 void hold_sample( uint8_t on )
591 PORTB |= (1 << SAMPLE_CONTROL);
592 DDRB |= (1 << SAMPLE_CONTROL);
596 DDRB |= (1 << SAMPLE_CONTROL);
597 PORTB &= ~(1 << SAMPLE_CONTROL);
602 void strobe_w( uint8_t strobe_num )
609 // Not all strobes are used depending on which are detected
610 switch ( strobe_num )
613 case 0: PORTD |= (1 << 0); break;
614 case 1: PORTD |= (1 << 1); break;
615 case 2: PORTD |= (1 << 2); break;
616 case 3: PORTD |= (1 << 3); break;
617 case 4: PORTD |= (1 << 4); break;
618 case 5: PORTD |= (1 << 5); break;
619 case 6: PORTD |= (1 << 6); break;
620 case 7: PORTD |= (1 << 7); break;
622 case 8: PORTE |= (1 << 0); break;
623 case 9: PORTE |= (1 << 1); break;
625 case 10: PORTC |= (1 << 0); break;
626 case 11: PORTC |= (1 << 1); break;
627 case 12: PORTC |= (1 << 2); break;
628 case 13: PORTC |= (1 << 3); break;
629 case 14: PORTC |= (1 << 4); break;
630 case 15: PORTC |= (1 << 5); break;
631 case 16: PORTC |= (1 << 6); break;
632 case 17: PORTC |= (1 << 7); break;
640 inline uint16_t getADC(void)
642 ADCSRA |= (1 << ADIF); // clear int flag by writing 1.
644 //wait for last read to complete.
645 while ( !( ADCSRA & (1 << ADIF) ) );
647 return ADC; // return sample
651 int sampleColumn_8x( uint8_t column, uint16_t * buffer )
653 // ensure all probe lines are driven low, and chill for recovery delay.
654 ADCSRA |= (1 << ADEN) | (1 << ADSC); // enable and start conversions
669 for ( uint8_t i = 0; i < STROBE_SETTLE; ++i ) { getADC(); }
676 for ( uint8_t mux = 0; mux < 8; ++mux )
678 SET_FULL_MUX(mux); // our sample will use this
680 // wait for mux to settle.
681 for ( uint8_t i = 0; i < MUX_SETTLE; ++i ) { getADC(); }
683 // retrieve current read.
684 buffer[mux] = getADC();
689 getADC(); // throw away; unknown mux.
691 SET_FULL_MUX(mux + 1); // our *next* sample will use this
693 // retrieve current read.
694 buffer[mux] = getADC();
704 ADCSRA &= ~(1 << ADEN);
706 // pull all columns' strobe-lines low.
719 int sampleColumn( uint8_t column )
723 rval = sampleColumn_8x( column, samples + SAMPLE_OFFSET );
729 uint8_t testColumn( uint8_t strobe )
733 for ( uint8_t mux = 0; mux < MUXES_COUNT; ++mux )
735 uint16_t delta = keys_averages[(strobe << MUXES_COUNT_XSHIFT) + mux];
737 uint8_t key = (strobe << MUXES_COUNT_XSHIFT) + mux;
740 if ( (db_sample = samples[SAMPLE_OFFSET + mux] >> 1) > (db_threshold = threshold) + (db_delta = delta) )
744 // Only register keypresses once the warmup is complete, or not enough debounce info
745 if ( boot_count >= WARMUP_LOOPS && keys_debounce[key] <= DEBOUNCE_THRESHOLD )
747 // Add to the Macro processing buffer if debounce criteria met
748 // Automatically handles converting to a USB code and sending off to the PC
749 if ( keys_debounce[key] == DEBOUNCE_THRESHOLD )
751 #define KEYSCAN_DEBOUNCE_DEBUG
752 #ifdef KEYSCAN_DEBOUNCE_DEBUG
755 printHex_op( key, 2 );
759 // Only add the key to the buffer once
760 // NOTE: Buffer can easily handle multiple adds, just more efficient
761 // and nicer debug messages :P
765 keys_debounce[key]++;
767 //#define KEYSCAN_THRESHOLD_DEBUG
768 #ifdef KEYSCAN_THRESHOLD_DEBUG
770 // <key> [<strobe>:<mux>] : <sense val> : <delta + threshold> : <margin>
772 printHex_op( key, 2 );
778 printHex( db_sample ); // Sense
780 printHex( db_threshold );
782 printHex( db_delta );
784 printHex( db_threshold + db_delta ); // Sense compare
786 printHex( db_sample - ( db_threshold + db_delta ) ); // Margin
791 // Clear debounce entry if no keypress detected
794 // If the key was previously pressed, remove from the buffer
795 for ( uint8_t c = 0; c < KeyIndex_BufferUsed; c++ )
797 // Key to release found
798 if ( KeyIndex_Buffer[c] == key )
800 // Shift keys from c position
801 for ( uint8_t k = c; k < KeyIndex_BufferUsed - 1; k++ )
802 KeyIndex_Buffer[k] = KeyIndex_Buffer[k + 1];
805 KeyIndex_BufferUsed--;
812 // Clear debounce entry
813 keys_debounce[key] = 0;
824 #ifdef DEBUG_FULL_SAMPLES_AVERAGES
825 // we don't want to debug-out during the measurements.
828 // Averages currently set per key
829 for ( int i = 0; i < KEY_COUNT; ++i )
835 else if ( !(i & 0x07) )
841 printHex( keys_averages[i] );
846 // Previously read full ADC scans?
847 for ( int i = 0; i< KEY_COUNT; ++i)
853 else if ( !(i & 0x07) )
859 printHex(full_samples[i]);
864 #ifdef DEBUG_STROBE_SAMPLES_AVERAGES
865 // Per strobe information
866 uint8_t cur_strober = ze_strober;
869 printHex(cur_strober);
871 // Previously read ADC scans on current strobe
873 for ( uint8_t i = 0; i < MUXES_COUNT; ++i )
876 printHex(full_samples[(cur_strober << MUXES_COUNT_XSHIFT) + i]);
879 // Averages current set on current strobe
882 for ( uint8_t i = 0; i < MUXES_COUNT; ++i )
885 printHex(keys_averages[(cur_strober << MUXES_COUNT_XSHIFT) + i]);
890 #ifdef DEBUG_DELTA_SAMPLE_THRESHOLD
892 printHex( db_delta );
894 printHex( db_sample );
896 printHex( db_threshold );
901 #ifdef DEBUG_USB_KEYMAP
904 // Current keymap values
905 for ( uint8_t i = 0; i < total_strobes; ++i )
907 printHex(cur_keymap[i]);