1 /* Copyright (C) 2014-2016 by Jacob Alexander
3 * Permission is hereby granted, free of charge, to any person obtaining a copy
4 * of this software and associated documentation files (the "Software"), to deal
5 * in the Software without restriction, including without limitation the rights
6 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
7 * copies of the Software, and to permit persons to whom the Software is
8 * furnished to do so, subject to the following conditions:
10 * The above copyright notice and this permission notice shall be included in
11 * all copies or substantial portions of the Software.
13 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
14 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
15 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
16 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
17 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
18 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22 // ----- Includes -----
25 #include <Lib/ScanLib.h>
33 #include <Lib/delay.h>
36 #include "matrix_scan.h"
38 // Matrix Configuration
43 // ----- Defines -----
45 #if ( DebounceThrottleDiv_define > 0 )
46 nat_ptr_t Matrix_divCounter = 0;
51 // ----- Function Declarations -----
54 void cliFunc_matrixDebug( char* args );
55 void cliFunc_matrixInfo( char* args );
56 void cliFunc_matrixState( char* args );
60 // ----- Variables -----
62 // Scan Module command dictionary
63 CLIDict_Entry( matrixDebug, "Enables matrix debug mode, prints out each scan code." NL "\t\tIf argument \033[35mT\033[0m is given, prints out each scan code state transition." );
64 CLIDict_Entry( matrixInfo, "Print info about the configured matrix." );
65 CLIDict_Entry( matrixState, "Prints out the current scan table N times." NL "\t\t \033[1mO\033[0m - Off, \033[1;33mP\033[0m - Press, \033[1;32mH\033[0m - Hold, \033[1;35mR\033[0m - Release, \033[1;31mI\033[0m - Invalid" );
67 CLIDict_Def( matrixCLIDict, "Matrix Module Commands" ) = {
68 CLIDict_Item( matrixDebug ),
69 CLIDict_Item( matrixInfo ),
70 CLIDict_Item( matrixState ),
71 { 0, 0, 0 } // Null entry for dictionary end
75 KeyState Matrix_scanArray[ Matrix_colsNum * Matrix_rowsNum ];
78 #ifdef GHOSTING_MATRIX
79 KeyGhost Matrix_ghostArray[ Matrix_colsNum * Matrix_rowsNum ];
81 uint8_t col_use[Matrix_colsNum], row_use[Matrix_rowsNum]; // used count
82 uint8_t col_ghost[Matrix_colsNum], row_ghost[Matrix_rowsNum]; // marked as having ghost if 1
86 // Matrix debug flag - If set to 1, for each keypress the scan code is displayed in hex
87 // If set to 2, for each key state change, the scan code is displayed along with the state
88 uint8_t matrixDebugMode = 0;
90 // Matrix State Table Debug Counter - If non-zero display state table after every matrix scan
91 uint16_t matrixDebugStateCounter = 0;
93 // Matrix Scan Counters
94 uint16_t matrixMaxScans = 0;
95 uint16_t matrixCurScans = 0;
96 uint16_t matrixPrevScans = 0;
98 // System Timer used for delaying debounce decisions
99 extern volatile uint32_t systick_millis_count;
103 // ----- Functions -----
105 // Pin action (Strobe, Sense, Strobe Setup, Sense Setup)
106 // NOTE: This function is highly dependent upon the organization of the register map
107 // Only guaranteed to work with Freescale MK20 series uCs
108 uint8_t Matrix_pin( GPIO_Pin gpio, Type type )
110 // Register width is defined as size of a pointer
111 unsigned int gpio_offset = gpio.port * 0x40 / sizeof(unsigned int*);
112 unsigned int port_offset = gpio.port * 0x1000 / sizeof(unsigned int*) + gpio.pin;
114 // Assumes 0x40 between GPIO Port registers and 0x1000 between PORT pin registers
116 volatile unsigned int *GPIO_PDDR = (unsigned int*)(&GPIOA_PDDR) + gpio_offset;
117 #ifndef GHOSTING_MATRIX
118 volatile unsigned int *GPIO_PSOR = (unsigned int*)(&GPIOA_PSOR) + gpio_offset;
120 volatile unsigned int *GPIO_PCOR = (unsigned int*)(&GPIOA_PCOR) + gpio_offset;
121 volatile unsigned int *GPIO_PDIR = (unsigned int*)(&GPIOA_PDIR) + gpio_offset;
122 volatile unsigned int *PORT_PCR = (unsigned int*)(&PORTA_PCR0) + port_offset;
124 // Operation depends on Type
128 #ifdef GHOSTING_MATRIX
129 *GPIO_PCOR |= (1 << gpio.pin);
130 *GPIO_PDDR |= (1 << gpio.pin); // output, low
132 *GPIO_PSOR |= (1 << gpio.pin);
137 #ifdef GHOSTING_MATRIX
138 // Ghosting martix needs to put not used (off) strobes in high impedance state
139 *GPIO_PDDR &= ~(1 << gpio.pin); // input, high Z state
141 *GPIO_PCOR |= (1 << gpio.pin);
144 case Type_StrobeSetup:
145 #ifdef GHOSTING_MATRIX
146 *GPIO_PDDR &= ~(1 << gpio.pin); // input, high Z state
147 *GPIO_PCOR |= (1 << gpio.pin);
150 *GPIO_PDDR |= (1 << gpio.pin);
153 // Configure pin with slow slew, high drive strength and GPIO mux
154 *PORT_PCR = PORT_PCR_SRE | PORT_PCR_DSE | PORT_PCR_MUX(1);
156 // Enabling open-drain if specified
157 switch ( Matrix_type )
159 case Config_Opendrain:
160 *PORT_PCR |= PORT_PCR_ODE;
163 // Do nothing otherwise
170 #ifdef GHOSTING_MATRIX // inverted
171 return *GPIO_PDIR & (1 << gpio.pin) ? 0 : 1;
173 return *GPIO_PDIR & (1 << gpio.pin) ? 1 : 0;
176 case Type_SenseSetup:
178 *GPIO_PDDR &= ~(1 << gpio.pin);
180 // Configure pin with passive filter and GPIO mux
181 *PORT_PCR = PORT_PCR_PFE | PORT_PCR_MUX(1);
183 // Pull resistor config
184 switch ( Matrix_type )
187 *PORT_PCR |= PORT_PCR_PE | PORT_PCR_PS;
190 case Config_Pulldown:
191 *PORT_PCR |= PORT_PCR_PE;
194 // Do nothing otherwise
204 // Setup GPIO pins for matrix scanning
207 // Register Matrix CLI dictionary
208 CLI_registerDictionary( matrixCLIDict, matrixCLIDictName );
211 for ( uint8_t pin = 0; pin < Matrix_colsNum; pin++ )
213 Matrix_pin( Matrix_cols[ pin ], Type_StrobeSetup );
217 for ( uint8_t pin = 0; pin < Matrix_rowsNum; pin++ )
219 Matrix_pin( Matrix_rows[ pin ], Type_SenseSetup );
222 // Clear out Debounce Array
223 for ( uint8_t item = 0; item < Matrix_maxKeys; item++ )
225 Matrix_scanArray[ item ].prevState = KeyState_Off;
226 Matrix_scanArray[ item ].curState = KeyState_Off;
227 Matrix_scanArray[ item ].activeCount = 0;
228 Matrix_scanArray[ item ].inactiveCount = DebounceDivThreshold_define; // Start at 'off' steady state
229 Matrix_scanArray[ item ].prevDecisionTime = 0;
230 #ifdef GHOSTING_MATRIX
231 Matrix_ghostArray[ item ].prev = KeyState_Off;
232 Matrix_ghostArray[ item ].cur = KeyState_Off;
233 Matrix_ghostArray[ item ].saved = KeyState_Off;
237 // Clear scan stats counters
242 void Matrix_keyPositionDebug( KeyPosition pos )
244 // Depending on the state, use a different flag + color
248 print("\033[1mO\033[0m");
252 print("\033[1;33mP\033[0m");
256 print("\033[1;32mH\033[0m");
259 case KeyState_Release:
260 print("\033[1;35mR\033[0m");
263 case KeyState_Invalid:
265 print("\033[1;31mI\033[0m");
271 // Scan the matrix for keypresses
272 // NOTE: scanNum should be reset to 0 after a USB send (to reset all the counters)
273 void Matrix_scan( uint16_t scanNum )
275 #if ( DebounceThrottleDiv_define > 0 )
276 // Scan-rate throttling
277 // By scanning using a divider, the scan rate slowed down
278 // DebounceThrottleDiv_define == 1 means -> /2 or half scan rate
279 // This helps with bouncy switches on fast uCs
280 if ( !( Matrix_divCounter++ & (1 << ( DebounceThrottleDiv_define - 1 )) ) )
284 // Increment stats counters
285 if ( scanNum > matrixMaxScans ) matrixMaxScans = scanNum;
288 matrixPrevScans = matrixCurScans;
296 // Read systick for event scheduling
297 uint8_t currentTime = (uint8_t)systick_millis_count;
299 // For each strobe, scan each of the sense pins
300 for ( uint8_t strobe = 0; strobe < Matrix_colsNum; strobe++ )
303 uint32_t start = micros();
304 while ((micros() - start) < STROBE_DELAY);
308 Matrix_pin( Matrix_cols[ strobe ], Type_StrobeOn );
312 while ((micros() - start) < STROBE_DELAY);
315 // Scan each of the sense pins
316 for ( uint8_t sense = 0; sense < Matrix_rowsNum; sense++ )
319 uint8_t key = Matrix_colsNum * sense + strobe;
320 KeyState *state = &Matrix_scanArray[ key ];
322 // If first scan, reset state
325 // Set previous state, and reset current state
326 state->prevState = state->curState;
327 state->curState = KeyState_Invalid;
331 // Increment count and right shift opposing count
332 // This means there is a maximum of scan 13 cycles on a perfect off to on transition
333 // (coming from a steady state 0xFFFF off scans)
334 // Somewhat longer with switch bounciness
335 // The advantage of this is that the count is ongoing and never needs to be reset
336 // State still needs to be kept track of to deal with what to send to the Macro module
337 if ( Matrix_pin( Matrix_rows[ sense ], Type_Sense ) )
339 // Only update if not going to wrap around
340 if ( state->activeCount < DebounceDivThreshold_define ) state->activeCount += 1;
341 state->inactiveCount >>= 1;
343 // Signal Not Detected
346 // Only update if not going to wrap around
347 if ( state->inactiveCount < DebounceDivThreshold_define ) state->inactiveCount += 1;
348 state->activeCount >>= 1;
351 // Check for state change if it hasn't been set
352 // But only if enough time has passed since last state change
353 // Only check if the minimum number of scans has been met
354 // the current state is invalid
355 // and either active or inactive count is over the debounce threshold
356 if ( state->curState == KeyState_Invalid )
358 // Determine time since last decision
359 uint8_t lastTransition = currentTime - state->prevDecisionTime;
361 // Attempt state transition
362 switch ( state->prevState )
366 if ( state->activeCount > state->inactiveCount )
368 state->curState = KeyState_Hold;
372 // If not enough time has passed since Hold
373 // Keep previous state
374 if ( lastTransition < MinDebounceTime_define )
376 //warn_print("FAST Release stopped");
377 state->curState = state->prevState;
381 state->curState = KeyState_Release;
385 case KeyState_Release:
387 if ( state->activeCount > state->inactiveCount )
389 // If not enough time has passed since Hold
390 // Keep previous state
391 if ( lastTransition < MinDebounceTime_define )
393 //warn_print("FAST Press stopped");
394 state->curState = state->prevState;
398 state->curState = KeyState_Press;
402 state->curState = KeyState_Off;
406 case KeyState_Invalid:
408 erro_print("Matrix scan bug!! Report me!");
412 // Update decision time
413 state->prevDecisionTime = currentTime;
415 // Send keystate to macro module
416 #ifndef GHOSTING_MATRIX
417 Macro_keyState( key, state->curState );
420 // Matrix Debug, only if there is a state change
421 if ( matrixDebugMode && state->curState != state->prevState )
423 // Basic debug output
424 if ( matrixDebugMode == 1 && state->curState == KeyState_Press )
429 // State transition debug output
430 else if ( matrixDebugMode == 2 )
433 Matrix_keyPositionDebug( state->curState );
441 Matrix_pin( Matrix_cols[ strobe ], Type_StrobeOff );
445 // Matrix ghosting check and elimination
446 // . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
447 #ifdef GHOSTING_MATRIX
448 // strobe = column, sense = row
450 // Count (rows) use for columns
452 for ( uint8_t col = 0; col < Matrix_colsNum; col++ )
455 for ( uint8_t row = 0; row < Matrix_rowsNum; row++ )
457 uint8_t key = Matrix_colsNum * row + col;
458 KeyState *state = &Matrix_scanArray[ key ];
459 if ( keyOn(state->curState) )
464 col_ghost[col] = 0; // clear
467 // Count (columns) use for rows
469 for ( uint8_t row = 0; row < Matrix_rowsNum; row++ )
472 for ( uint8_t col = 0; col < Matrix_colsNum; col++ )
474 uint8_t key = Matrix_colsNum * row + col;
475 KeyState *state = &Matrix_scanArray[ key ];
476 if ( keyOn(state->curState) )
481 row_ghost[row] = 0; // clear
484 // Check if matrix has ghost
485 // Happens when key is pressed and some other key is pressed in same row and another in same column
487 for ( uint8_t col = 0; col < Matrix_colsNum; col++ )
489 for ( uint8_t row = 0; row < Matrix_rowsNum; row++ )
491 uint8_t key = Matrix_colsNum * row + col;
492 KeyState *state = &Matrix_scanArray[ key ];
493 if ( keyOn(state->curState) && col_use[col] >= 2 && row_use[row] >= 2 )
495 // mark col and row as having ghost
498 //print(" "); printInt8(col); print(","); printInt8(row);
505 for ( uint8_t col = 0; col < Matrix_colsNum; col++ )
507 for ( uint8_t row = 0; row < Matrix_rowsNum; row++ )
509 uint8_t key = Matrix_colsNum * row + col;
510 KeyState *state = &Matrix_scanArray[ key ];
511 KeyGhost *st = &Matrix_ghostArray[ key ];
513 // col or row is ghosting (crossed)
514 uint8_t ghost = (col_ghost[col] > 0 || row_ghost[row] > 0) ? 1 : 0;
516 st->prev = st->cur; // previous
517 // save state if no ghost or outside ghosted area
519 st->saved = state->curState; // save state if no ghost
521 // use saved state if ghosting, or current if not
522 st->cur = ghost > 0 ? st->saved : state->curState;
524 // Send keystate to macro module
525 KeyPosition k = !st->cur
526 ? (!st->prev ? KeyState_Off : KeyState_Release)
527 : ( st->prev ? KeyState_Hold : KeyState_Press);
528 Macro_keyState( key, k );
532 // . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
535 // State Table Output Debug
536 if ( matrixDebugStateCounter > 0 )
539 matrixDebugStateCounter--;
541 // Output stats on number of scans being done per USB send
543 info_msg("Max scans: ");
544 printHex( matrixMaxScans );
546 info_msg("Previous scans: ");
547 printHex( matrixPrevScans );
550 // Output current scan number
551 info_msg("Scan Number: ");
555 // Display the state info for each key
556 print("<key>:<previous state><current state> <active count> <inactive count>");
557 for ( uint8_t key = 0; key < Matrix_maxKeys; key++ )
559 // Every 4 keys, put a newline
564 printHex_op( key, 2 );
567 Matrix_keyPositionDebug( Matrix_scanArray[ key ].prevState );
568 Matrix_keyPositionDebug( Matrix_scanArray[ key ].curState );
570 printHex_op( Matrix_scanArray[ key ].activeCount, 4 );
572 printHex_op( Matrix_scanArray[ key ].inactiveCount, 4 );
581 // Called by parent scan module whenever the available current changes
583 void Matrix_currentChange( unsigned int current )
585 // TODO - Any potential power savings?
590 // ----- CLI Command Functions -----
592 void cliFunc_matrixInfo( char* args )
595 info_msg("Columns: ");
596 printHex( Matrix_colsNum );
600 printHex( Matrix_rowsNum );
603 info_msg("Max Keys: ");
604 printHex( Matrix_maxKeys );
607 void cliFunc_matrixDebug( char* args )
609 // Parse number from argument
610 // NOTE: Only first argument is used
613 CLI_argumentIsolation( args, &arg1Ptr, &arg2Ptr );
615 // Set the matrix debug flag depending on the argument
616 // If no argument, set to scan code only
617 // If set to T, set to state transition
618 switch ( arg1Ptr[0] )
623 matrixDebugMode = matrixDebugMode != 2 ? 2 : 0;
628 matrixDebugMode = matrixDebugMode != 1 ? 1 : 0;
637 info_msg("Matrix Debug Mode: ");
638 printInt8( matrixDebugMode );
641 void cliFunc_matrixState( char* args )
643 // Parse number from argument
644 // NOTE: Only first argument is used
647 CLI_argumentIsolation( args, &arg1Ptr, &arg2Ptr );
649 // Default to 1 if no argument is given
650 matrixDebugStateCounter = 1;
652 if ( arg1Ptr[0] != '\0' )
654 matrixDebugStateCounter = (uint16_t)numToInt( arg1Ptr );