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_matrixState( char* args );
59 // ----- Variables -----
61 // Scan Module command dictionary
62 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." );
63 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" );
65 CLIDict_Def( matrixCLIDict, "Matrix Module Commands" ) = {
66 CLIDict_Item( matrixDebug ),
67 CLIDict_Item( matrixState ),
68 { 0, 0, 0 } // Null entry for dictionary end
72 KeyState Matrix_scanArray[ Matrix_colsNum * Matrix_rowsNum ];
75 #ifdef GHOSTING_MATRIX
76 KeyGhost Matrix_ghostArray[ Matrix_colsNum * Matrix_rowsNum ];
78 uint8_t col_use[Matrix_colsNum], row_use[Matrix_rowsNum]; // used count
79 uint8_t col_ghost[Matrix_colsNum], row_ghost[Matrix_rowsNum]; // marked as having ghost if 1
83 // Matrix debug flag - If set to 1, for each keypress the scan code is displayed in hex
84 // If set to 2, for each key state change, the scan code is displayed along with the state
85 uint8_t matrixDebugMode = 0;
87 // Matrix State Table Debug Counter - If non-zero display state table after every matrix scan
88 uint16_t matrixDebugStateCounter = 0;
90 // Matrix Scan Counters
91 uint16_t matrixMaxScans = 0;
92 uint16_t matrixCurScans = 0;
93 uint16_t matrixPrevScans = 0;
95 // System Timer used for delaying debounce decisions
96 extern volatile uint32_t systick_millis_count;
100 // ----- Functions -----
102 // Pin action (Strobe, Sense, Strobe Setup, Sense Setup)
103 // NOTE: This function is highly dependent upon the organization of the register map
104 // Only guaranteed to work with Freescale MK20 series uCs
105 uint8_t Matrix_pin( GPIO_Pin gpio, Type type )
107 // Register width is defined as size of a pointer
108 unsigned int gpio_offset = gpio.port * 0x40 / sizeof(unsigned int*);
109 unsigned int port_offset = gpio.port * 0x1000 / sizeof(unsigned int*) + gpio.pin;
111 // Assumes 0x40 between GPIO Port registers and 0x1000 between PORT pin registers
113 volatile unsigned int *GPIO_PDDR = (unsigned int*)(&GPIOA_PDDR) + gpio_offset;
114 #ifndef GHOSTING_MATRIX
115 volatile unsigned int *GPIO_PSOR = (unsigned int*)(&GPIOA_PSOR) + gpio_offset;
117 volatile unsigned int *GPIO_PCOR = (unsigned int*)(&GPIOA_PCOR) + gpio_offset;
118 volatile unsigned int *GPIO_PDIR = (unsigned int*)(&GPIOA_PDIR) + gpio_offset;
119 volatile unsigned int *PORT_PCR = (unsigned int*)(&PORTA_PCR0) + port_offset;
121 // Operation depends on Type
125 #ifdef GHOSTING_MATRIX
126 *GPIO_PCOR |= (1 << gpio.pin);
127 *GPIO_PDDR |= (1 << gpio.pin); // output, low
129 *GPIO_PSOR |= (1 << gpio.pin);
134 #ifdef GHOSTING_MATRIX
135 // Ghosting martix needs to put not used (off) strobes in high impedance state
136 *GPIO_PDDR &= ~(1 << gpio.pin); // input, high Z state
138 *GPIO_PCOR |= (1 << gpio.pin);
141 case Type_StrobeSetup:
142 #ifdef GHOSTING_MATRIX
143 *GPIO_PDDR &= ~(1 << gpio.pin); // input, high Z state
144 *GPIO_PCOR |= (1 << gpio.pin);
147 *GPIO_PDDR |= (1 << gpio.pin);
150 // Configure pin with slow slew, high drive strength and GPIO mux
151 *PORT_PCR = PORT_PCR_SRE | PORT_PCR_DSE | PORT_PCR_MUX(1);
153 // Enabling open-drain if specified
154 switch ( Matrix_type )
156 case Config_Opendrain:
157 *PORT_PCR |= PORT_PCR_ODE;
160 // Do nothing otherwise
167 #ifdef GHOSTING_MATRIX // inverted
168 return *GPIO_PDIR & (1 << gpio.pin) ? 0 : 1;
170 return *GPIO_PDIR & (1 << gpio.pin) ? 1 : 0;
173 case Type_SenseSetup:
175 *GPIO_PDDR &= ~(1 << gpio.pin);
177 // Configure pin with passive filter and GPIO mux
178 *PORT_PCR = PORT_PCR_PFE | PORT_PCR_MUX(1);
180 // Pull resistor config
181 switch ( Matrix_type )
184 *PORT_PCR |= PORT_PCR_PE | PORT_PCR_PS;
187 case Config_Pulldown:
188 *PORT_PCR |= PORT_PCR_PE;
191 // Do nothing otherwise
201 // Setup GPIO pins for matrix scanning
204 // Register Matrix CLI dictionary
205 CLI_registerDictionary( matrixCLIDict, matrixCLIDictName );
207 info_msg("Columns: ");
208 printHex( Matrix_colsNum );
211 for ( uint8_t pin = 0; pin < Matrix_colsNum; pin++ )
213 Matrix_pin( Matrix_cols[ pin ], Type_StrobeSetup );
218 printHex( Matrix_rowsNum );
221 for ( uint8_t pin = 0; pin < Matrix_rowsNum; pin++ )
223 Matrix_pin( Matrix_rows[ pin ], Type_SenseSetup );
227 info_msg("Max Keys: ");
228 printHex( Matrix_maxKeys );
231 // Clear out Debounce Array
232 for ( uint8_t item = 0; item < Matrix_maxKeys; item++ )
234 Matrix_scanArray[ item ].prevState = KeyState_Off;
235 Matrix_scanArray[ item ].curState = KeyState_Off;
236 Matrix_scanArray[ item ].activeCount = 0;
237 Matrix_scanArray[ item ].inactiveCount = DebounceDivThreshold_define; // Start at 'off' steady state
238 Matrix_scanArray[ item ].prevDecisionTime = 0;
239 #ifdef GHOSTING_MATRIX
240 Matrix_ghostArray[ item ].prev = KeyState_Off;
241 Matrix_ghostArray[ item ].cur = KeyState_Off;
242 Matrix_ghostArray[ item ].saved = KeyState_Off;
246 // Clear scan stats counters
251 void Matrix_keyPositionDebug( KeyPosition pos )
253 // Depending on the state, use a different flag + color
257 print("\033[1mO\033[0m");
261 print("\033[1;33mP\033[0m");
265 print("\033[1;32mH\033[0m");
268 case KeyState_Release:
269 print("\033[1;35mR\033[0m");
272 case KeyState_Invalid:
274 print("\033[1;31mI\033[0m");
280 // Scan the matrix for keypresses
281 // NOTE: scanNum should be reset to 0 after a USB send (to reset all the counters)
282 void Matrix_scan( uint16_t scanNum )
284 #if ( DebounceThrottleDiv_define > 0 )
285 // Scan-rate throttling
286 // By scanning using a divider, the scan rate slowed down
287 // DebounceThrottleDiv_define == 1 means -> /2 or half scan rate
288 // This helps with bouncy switches on fast uCs
289 if ( !( Matrix_divCounter++ & (1 << ( DebounceThrottleDiv_define - 1 )) ) )
293 // Increment stats counters
294 if ( scanNum > matrixMaxScans ) matrixMaxScans = scanNum;
297 matrixPrevScans = matrixCurScans;
305 // Read systick for event scheduling
306 uint8_t currentTime = (uint8_t)systick_millis_count;
308 // For each strobe, scan each of the sense pins
309 for ( uint8_t strobe = 0; strobe < Matrix_colsNum; strobe++ )
312 uint32_t start = micros();
313 while ((micros() - start) < STROBE_DELAY);
317 Matrix_pin( Matrix_cols[ strobe ], Type_StrobeOn );
321 while ((micros() - start) < STROBE_DELAY);
324 // Scan each of the sense pins
325 for ( uint8_t sense = 0; sense < Matrix_rowsNum; sense++ )
328 uint8_t key = Matrix_colsNum * sense + strobe;
329 KeyState *state = &Matrix_scanArray[ key ];
331 // If first scan, reset state
334 // Set previous state, and reset current state
335 state->prevState = state->curState;
336 state->curState = KeyState_Invalid;
340 // Increment count and right shift opposing count
341 // This means there is a maximum of scan 13 cycles on a perfect off to on transition
342 // (coming from a steady state 0xFFFF off scans)
343 // Somewhat longer with switch bounciness
344 // The advantage of this is that the count is ongoing and never needs to be reset
345 // State still needs to be kept track of to deal with what to send to the Macro module
346 if ( Matrix_pin( Matrix_rows[ sense ], Type_Sense ) )
348 // Only update if not going to wrap around
349 if ( state->activeCount < DebounceDivThreshold_define ) state->activeCount += 1;
350 state->inactiveCount >>= 1;
352 // Signal Not Detected
355 // Only update if not going to wrap around
356 if ( state->inactiveCount < DebounceDivThreshold_define ) state->inactiveCount += 1;
357 state->activeCount >>= 1;
360 // Check for state change if it hasn't been set
361 // But only if enough time has passed since last state change
362 // Only check if the minimum number of scans has been met
363 // the current state is invalid
364 // and either active or inactive count is over the debounce threshold
365 if ( state->curState == KeyState_Invalid )
367 // Determine time since last decision
368 uint8_t lastTransition = currentTime - state->prevDecisionTime;
370 // Attempt state transition
371 switch ( state->prevState )
375 if ( state->activeCount > state->inactiveCount )
377 state->curState = KeyState_Hold;
381 // If not enough time has passed since Hold
382 // Keep previous state
383 if ( lastTransition < MinDebounceTime_define )
385 //warn_print("FAST Release stopped");
386 state->curState = state->prevState;
390 state->curState = KeyState_Release;
394 case KeyState_Release:
396 if ( state->activeCount > state->inactiveCount )
398 // If not enough time has passed since Hold
399 // Keep previous state
400 if ( lastTransition < MinDebounceTime_define )
402 //warn_print("FAST Press stopped");
403 state->curState = state->prevState;
407 state->curState = KeyState_Press;
411 state->curState = KeyState_Off;
415 case KeyState_Invalid:
417 erro_print("Matrix scan bug!! Report me!");
421 // Update decision time
422 state->prevDecisionTime = currentTime;
424 // Send keystate to macro module
425 #ifndef GHOSTING_MATRIX
426 Macro_keyState( key, state->curState );
429 // Matrix Debug, only if there is a state change
430 if ( matrixDebugMode && state->curState != state->prevState )
432 // Basic debug output
433 if ( matrixDebugMode == 1 && state->curState == KeyState_Press )
438 // State transition debug output
439 else if ( matrixDebugMode == 2 )
442 Matrix_keyPositionDebug( state->curState );
450 Matrix_pin( Matrix_cols[ strobe ], Type_StrobeOff );
454 // Matrix ghosting check and elimination
455 // . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
456 #ifdef GHOSTING_MATRIX
457 // strobe = column, sense = row
459 // Count (rows) use for columns
461 for ( uint8_t col = 0; col < Matrix_colsNum; col++ )
464 for ( uint8_t row = 0; row < Matrix_rowsNum; row++ )
466 uint8_t key = Matrix_colsNum * row + col;
467 KeyState *state = &Matrix_scanArray[ key ];
468 if ( keyOn(state->curState) )
473 col_ghost[col] = 0; // clear
476 // Count (columns) use for rows
478 for ( uint8_t row = 0; row < Matrix_rowsNum; row++ )
481 for ( uint8_t col = 0; col < Matrix_colsNum; col++ )
483 uint8_t key = Matrix_colsNum * row + col;
484 KeyState *state = &Matrix_scanArray[ key ];
485 if ( keyOn(state->curState) )
490 row_ghost[row] = 0; // clear
493 // Check if matrix has ghost
494 // Happens when key is pressed and some other key is pressed in same row and another in same column
496 for ( uint8_t col = 0; col < Matrix_colsNum; col++ )
498 for ( uint8_t row = 0; row < Matrix_rowsNum; row++ )
500 uint8_t key = Matrix_colsNum * row + col;
501 KeyState *state = &Matrix_scanArray[ key ];
502 if ( keyOn(state->curState) && col_use[col] >= 2 && row_use[row] >= 2 )
504 // mark col and row as having ghost
507 //print(" "); printInt8(col); print(","); printInt8(row);
514 for ( uint8_t col = 0; col < Matrix_colsNum; col++ )
516 for ( uint8_t row = 0; row < Matrix_rowsNum; row++ )
518 uint8_t key = Matrix_colsNum * row + col;
519 KeyState *state = &Matrix_scanArray[ key ];
520 KeyGhost *st = &Matrix_ghostArray[ key ];
522 // col or row is ghosting (crossed)
523 uint8_t ghost = (col_ghost[col] > 0 || row_ghost[row] > 0) ? 1 : 0;
525 st->prev = st->cur; // previous
526 // save state if no ghost or outside ghosted area
528 st->saved = state->curState; // save state if no ghost
530 // use saved state if ghosting, or current if not
531 st->cur = ghost > 0 ? st->saved : state->curState;
533 // Send keystate to macro module
534 KeyPosition k = !st->cur
535 ? (!st->prev ? KeyState_Off : KeyState_Release)
536 : ( st->prev ? KeyState_Hold : KeyState_Press);
537 Macro_keyState( key, k );
541 // . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
544 // State Table Output Debug
545 if ( matrixDebugStateCounter > 0 )
548 matrixDebugStateCounter--;
550 // Output stats on number of scans being done per USB send
552 info_msg("Max scans: ");
553 printHex( matrixMaxScans );
555 info_msg("Previous scans: ");
556 printHex( matrixPrevScans );
559 // Output current scan number
560 info_msg("Scan Number: ");
564 // Display the state info for each key
565 print("<key>:<previous state><current state> <active count> <inactive count>");
566 for ( uint8_t key = 0; key < Matrix_maxKeys; key++ )
568 // Every 4 keys, put a newline
573 printHex_op( key, 2 );
576 Matrix_keyPositionDebug( Matrix_scanArray[ key ].prevState );
577 Matrix_keyPositionDebug( Matrix_scanArray[ key ].curState );
579 printHex_op( Matrix_scanArray[ key ].activeCount, 4 );
581 printHex_op( Matrix_scanArray[ key ].inactiveCount, 4 );
590 // Called by parent scan module whenever the available current changes
592 void Matrix_currentChange( unsigned int current )
594 // TODO - Any potential power savings?
599 // ----- CLI Command Functions -----
601 void cliFunc_matrixDebug ( char* args )
603 // Parse number from argument
604 // NOTE: Only first argument is used
607 CLI_argumentIsolation( args, &arg1Ptr, &arg2Ptr );
609 // Set the matrix debug flag depending on the argument
610 // If no argument, set to scan code only
611 // If set to T, set to state transition
612 switch ( arg1Ptr[0] )
617 matrixDebugMode = matrixDebugMode != 2 ? 2 : 0;
622 matrixDebugMode = matrixDebugMode != 1 ? 1 : 0;
631 info_msg("Matrix Debug Mode: ");
632 printInt8( matrixDebugMode );
635 void cliFunc_matrixState ( char* args )
637 // Parse number from argument
638 // NOTE: Only first argument is used
641 CLI_argumentIsolation( args, &arg1Ptr, &arg2Ptr );
643 // Default to 1 if no argument is given
644 matrixDebugStateCounter = 1;
646 if ( arg1Ptr[0] != '\0' )
648 matrixDebugStateCounter = (uint16_t)numToInt( arg1Ptr );