1 /* Copyright (C) 2014-2015 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>
35 #include "matrix_scan.h"
37 // Matrix Configuration
42 // ----- Defines -----
44 #if ( DebounceThrottleDiv_define > 0 )
45 nat_ptr_t Matrix_divCounter = 0;
50 // ----- Function Declarations -----
53 void cliFunc_matrixDebug( char* args );
54 void cliFunc_matrixState( char* args );
58 // ----- Variables -----
60 // Scan Module command dictionary
61 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." );
62 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" );
64 CLIDict_Def( matrixCLIDict, "Matrix Module Commands" ) = {
65 CLIDict_Item( matrixDebug ),
66 CLIDict_Item( matrixState ),
67 { 0, 0, 0 } // Null entry for dictionary end
71 KeyState Matrix_scanArray[ Matrix_colsNum * Matrix_rowsNum ];
73 // Matrix debug flag - If set to 1, for each keypress the scan code is displayed in hex
74 // If set to 2, for each key state change, the scan code is displayed along with the state
75 uint8_t matrixDebugMode = 0;
77 // Matrix State Table Debug Counter - If non-zero display state table after every matrix scan
78 uint16_t matrixDebugStateCounter = 0;
80 // Matrix Scan Counters
81 uint16_t matrixMaxScans = 0;
82 uint16_t matrixCurScans = 0;
83 uint16_t matrixPrevScans = 0;
85 // System Timer used for delaying debounce decisions
86 extern volatile uint32_t systick_millis_count;
90 // ----- Functions -----
92 // Pin action (Strobe, Sense, Strobe Setup, Sense Setup)
93 // NOTE: This function is highly dependent upon the organization of the register map
94 // Only guaranteed to work with Freescale MK20 series uCs
95 uint8_t Matrix_pin( GPIO_Pin gpio, Type type )
97 // Register width is defined as size of a pointer
98 unsigned int gpio_offset = gpio.port * 0x40 / sizeof(unsigned int*);
99 unsigned int port_offset = gpio.port * 0x1000 / sizeof(unsigned int*) + gpio.pin;
101 // Assumes 0x40 between GPIO Port registers and 0x1000 between PORT pin registers
103 volatile unsigned int *GPIO_PDDR = (unsigned int*)(&GPIOA_PDDR) + gpio_offset;
104 volatile unsigned int *GPIO_PSOR = (unsigned int*)(&GPIOA_PSOR) + gpio_offset;
105 volatile unsigned int *GPIO_PCOR = (unsigned int*)(&GPIOA_PCOR) + gpio_offset;
106 volatile unsigned int *GPIO_PDIR = (unsigned int*)(&GPIOA_PDIR) + gpio_offset;
107 volatile unsigned int *PORT_PCR = (unsigned int*)(&PORTA_PCR0) + port_offset;
109 // Operation depends on Type
113 *GPIO_PSOR |= (1 << gpio.pin);
117 *GPIO_PCOR |= (1 << gpio.pin);
120 case Type_StrobeSetup:
122 *GPIO_PDDR |= (1 << gpio.pin);
124 // Configure pin with slow slew, high drive strength and GPIO mux
125 *PORT_PCR = PORT_PCR_SRE | PORT_PCR_DSE | PORT_PCR_MUX(1);
127 // Enabling open-drain if specified
128 switch ( Matrix_type )
130 case Config_Opendrain:
131 *PORT_PCR |= PORT_PCR_ODE;
134 // Do nothing otherwise
141 return *GPIO_PDIR & (1 << gpio.pin) ? 1 : 0;
143 case Type_SenseSetup:
145 *GPIO_PDDR &= ~(1 << gpio.pin);
147 // Configure pin with passive filter and GPIO mux
148 *PORT_PCR = PORT_PCR_PFE | PORT_PCR_MUX(1);
150 // Pull resistor config
151 switch ( Matrix_type )
154 *PORT_PCR |= PORT_PCR_PE | PORT_PCR_PS;
157 case Config_Pulldown:
158 *PORT_PCR |= PORT_PCR_PE;
161 // Do nothing otherwise
171 // Setup GPIO pins for matrix scanning
174 // Register Matrix CLI dictionary
175 CLI_registerDictionary( matrixCLIDict, matrixCLIDictName );
177 info_msg("Columns: ");
178 printHex( Matrix_colsNum );
181 for ( uint8_t pin = 0; pin < Matrix_colsNum; pin++ )
183 Matrix_pin( Matrix_cols[ pin ], Type_StrobeSetup );
188 printHex( Matrix_rowsNum );
191 for ( uint8_t pin = 0; pin < Matrix_rowsNum; pin++ )
193 Matrix_pin( Matrix_rows[ pin ], Type_SenseSetup );
197 info_msg("Max Keys: ");
198 printHex( Matrix_maxKeys );
201 // Clear out Debounce Array
202 for ( uint8_t item = 0; item < Matrix_maxKeys; item++ )
204 Matrix_scanArray[ item ].prevState = KeyState_Off;
205 Matrix_scanArray[ item ].curState = KeyState_Off;
206 Matrix_scanArray[ item ].activeCount = 0;
207 Matrix_scanArray[ item ].inactiveCount = DebounceDivThreshold_define; // Start at 'off' steady state
208 Matrix_scanArray[ item ].prevDecisionTime = 0;
211 // Clear scan stats counters
216 void Matrix_keyPositionDebug( KeyPosition pos )
218 // Depending on the state, use a different flag + color
222 print("\033[1mO\033[0m");
226 print("\033[1;33mP\033[0m");
230 print("\033[1;32mH\033[0m");
233 case KeyState_Release:
234 print("\033[1;35mR\033[0m");
237 case KeyState_Invalid:
239 print("\033[1;31mI\033[0m");
245 // Scan the matrix for keypresses
246 // NOTE: scanNum should be reset to 0 after a USB send (to reset all the counters)
247 void Matrix_scan( uint16_t scanNum )
249 #if ( DebounceThrottleDiv_define > 0 )
250 // Scan-rate throttling
251 // By scanning using a divider, the scan rate slowed down
252 // DebounceThrottleDiv_define == 1 means -> /2 or half scan rate
253 // This helps with bouncy switches on fast uCs
254 if ( !( Matrix_divCounter++ & (1 << ( DebounceThrottleDiv_define - 1 )) ) )
258 // Increment stats counters
259 if ( scanNum > matrixMaxScans ) matrixMaxScans = scanNum;
262 matrixPrevScans = matrixCurScans;
270 // Read systick for event scheduling
271 uint8_t currentTime = (uint8_t)systick_millis_count;
273 // For each strobe, scan each of the sense pins
274 for ( uint8_t strobe = 0; strobe < Matrix_colsNum; strobe++ )
277 Matrix_pin( Matrix_cols[ strobe ], Type_StrobeOn );
279 // Scan each of the sense pins
280 for ( uint8_t sense = 0; sense < Matrix_rowsNum; sense++ )
283 uint8_t key = Matrix_colsNum * sense + strobe;
284 KeyState *state = &Matrix_scanArray[ key ];
286 // If first scan, reset state
289 // Set previous state, and reset current state
290 state->prevState = state->curState;
291 state->curState = KeyState_Invalid;
295 // Increment count and right shift opposing count
296 // This means there is a maximum of scan 13 cycles on a perfect off to on transition
297 // (coming from a steady state 0xFFFF off scans)
298 // Somewhat longer with switch bounciness
299 // The advantage of this is that the count is ongoing and never needs to be reset
300 // State still needs to be kept track of to deal with what to send to the Macro module
301 if ( Matrix_pin( Matrix_rows[ sense ], Type_Sense ) )
303 // Only update if not going to wrap around
304 if ( state->activeCount < DebounceDivThreshold_define ) state->activeCount += 1;
305 state->inactiveCount >>= 1;
307 // Signal Not Detected
310 // Only update if not going to wrap around
311 if ( state->inactiveCount < DebounceDivThreshold_define ) state->inactiveCount += 1;
312 state->activeCount >>= 1;
315 // Check for state change if it hasn't been set
316 // But only if enough time has passed since last state change
317 // Only check if the minimum number of scans has been met
318 // the current state is invalid
319 // and either active or inactive count is over the debounce threshold
320 if ( state->curState == KeyState_Invalid )
322 // Determine time since last decision
323 uint8_t lastTransition = currentTime - state->prevDecisionTime;
325 // Attempt state transition
326 switch ( state->prevState )
330 if ( state->activeCount > state->inactiveCount )
332 state->curState = KeyState_Hold;
336 // If not enough time has passed since Hold
337 // Keep previous state
338 if ( lastTransition < MinDebounceTime_define )
340 //warn_print("FAST Release stopped");
341 state->curState = state->prevState;
345 state->curState = KeyState_Release;
349 case KeyState_Release:
351 if ( state->activeCount > state->inactiveCount )
353 // If not enough time has passed since Hold
354 // Keep previous state
355 if ( lastTransition < MinDebounceTime_define )
357 //warn_print("FAST Press stopped");
358 state->curState = state->prevState;
362 state->curState = KeyState_Press;
366 state->curState = KeyState_Off;
370 case KeyState_Invalid:
372 erro_print("Matrix scan bug!! Report me!");
376 // Update decision time
377 state->prevDecisionTime = currentTime;
379 // Send keystate to macro module
380 Macro_keyState( key, state->curState );
382 // Matrix Debug, only if there is a state change
383 if ( matrixDebugMode && state->curState != state->prevState )
385 // Basic debug output
386 if ( matrixDebugMode == 1 && state->curState == KeyState_Press )
391 // State transition debug output
392 else if ( matrixDebugMode == 2 )
395 Matrix_keyPositionDebug( state->curState );
403 Matrix_pin( Matrix_cols[ strobe ], Type_StrobeOff );
406 // State Table Output Debug
407 if ( matrixDebugStateCounter > 0 )
410 matrixDebugStateCounter--;
412 // Output stats on number of scans being done per USB send
414 info_msg("Max scans: ");
415 printHex( matrixMaxScans );
417 info_msg("Previous scans: ");
418 printHex( matrixPrevScans );
421 // Output current scan number
422 info_msg("Scan Number: ");
426 // Display the state info for each key
427 print("<key>:<previous state><current state> <active count> <inactive count>");
428 for ( uint8_t key = 0; key < Matrix_maxKeys; key++ )
430 // Every 4 keys, put a newline
435 printHex_op( key, 2 );
438 Matrix_keyPositionDebug( Matrix_scanArray[ key ].prevState );
439 Matrix_keyPositionDebug( Matrix_scanArray[ key ].curState );
441 printHex_op( Matrix_scanArray[ key ].activeCount, 4 );
443 printHex_op( Matrix_scanArray[ key ].inactiveCount, 4 );
452 // ----- CLI Command Functions -----
454 void cliFunc_matrixDebug ( char* args )
456 // Parse number from argument
457 // NOTE: Only first argument is used
460 CLI_argumentIsolation( args, &arg1Ptr, &arg2Ptr );
462 // Set the matrix debug flag depending on the argument
463 // If no argument, set to scan code only
464 // If set to T, set to state transition
465 switch ( arg1Ptr[0] )
470 matrixDebugMode = matrixDebugMode != 2 ? 2 : 0;
475 matrixDebugMode = matrixDebugMode != 1 ? 1 : 0;
484 info_msg("Matrix Debug Mode: ");
485 printInt8( matrixDebugMode );
488 void cliFunc_matrixState ( char* args )
490 // Parse number from argument
491 // NOTE: Only first argument is used
494 CLI_argumentIsolation( args, &arg1Ptr, &arg2Ptr );
496 // Default to 1 if no argument is given
497 matrixDebugStateCounter = 1;
499 if ( arg1Ptr[0] != '\0' )
501 matrixDebugStateCounter = (uint16_t)numToInt( arg1Ptr );