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>
34 #include "matrix_scan.h"
36 // Matrix Configuration
41 // ----- Function Declarations -----
44 void cliFunc_matrixDebug( char* args );
45 void cliFunc_matrixState( char* args );
49 // ----- Variables -----
51 // Scan Module command dictionary
52 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." );
53 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" );
55 CLIDict_Def( matrixCLIDict, "Matrix Module Commands" ) = {
56 CLIDict_Item( matrixDebug ),
57 CLIDict_Item( matrixState ),
58 { 0, 0, 0 } // Null entry for dictionary end
62 KeyState Matrix_scanArray[ Matrix_colsNum * Matrix_rowsNum ];
64 // Matrix debug flag - If set to 1, for each keypress the scan code is displayed in hex
65 // If set to 2, for each key state change, the scan code is displayed along with the state
66 uint8_t matrixDebugMode = 0;
68 // Matrix State Table Debug Counter - If non-zero display state table after every matrix scan
69 uint16_t matrixDebugStateCounter = 0;
71 // Matrix Scan Counters
72 uint16_t matrixMaxScans = 0;
73 uint16_t matrixCurScans = 0;
74 uint16_t matrixPrevScans = 0;
78 // ----- Functions -----
80 // Pin action (Strobe, Sense, Strobe Setup, Sense Setup)
81 // NOTE: This function is highly dependent upon the organization of the register map
82 // Only guaranteed to work with Freescale MK20 series uCs
83 uint8_t Matrix_pin( GPIO_Pin gpio, Type type )
85 // Register width is defined as size of a pointer
86 unsigned int gpio_offset = gpio.port * 0x40 / sizeof(unsigned int*);
87 unsigned int port_offset = gpio.port * 0x1000 / sizeof(unsigned int*) + gpio.pin;
89 // Assumes 0x40 between GPIO Port registers and 0x1000 between PORT pin registers
91 volatile unsigned int *GPIO_PDDR = (unsigned int*)(&GPIOA_PDDR) + gpio_offset;
92 volatile unsigned int *GPIO_PSOR = (unsigned int*)(&GPIOA_PSOR) + gpio_offset;
93 volatile unsigned int *GPIO_PCOR = (unsigned int*)(&GPIOA_PCOR) + gpio_offset;
94 volatile unsigned int *GPIO_PDIR = (unsigned int*)(&GPIOA_PDIR) + gpio_offset;
95 volatile unsigned int *PORT_PCR = (unsigned int*)(&PORTA_PCR0) + port_offset;
97 // Operation depends on Type
101 *GPIO_PSOR |= (1 << gpio.pin);
105 *GPIO_PCOR |= (1 << gpio.pin);
108 case Type_StrobeSetup:
110 *GPIO_PDDR |= (1 << gpio.pin);
112 // Configure pin with slow slew, high drive strength and GPIO mux
113 *PORT_PCR = PORT_PCR_SRE | PORT_PCR_DSE | PORT_PCR_MUX(1);
115 // Enabling open-drain if specified
116 switch ( Matrix_type )
118 case Config_Opendrain:
119 *PORT_PCR |= PORT_PCR_ODE;
122 // Do nothing otherwise
129 return *GPIO_PDIR & (1 << gpio.pin) ? 1 : 0;
131 case Type_SenseSetup:
133 *GPIO_PDDR &= ~(1 << gpio.pin);
135 // Configure pin with passive filter and GPIO mux
136 *PORT_PCR = PORT_PCR_PFE | PORT_PCR_MUX(1);
138 // Pull resistor config
139 switch ( Matrix_type )
142 *PORT_PCR |= PORT_PCR_PE | PORT_PCR_PS;
145 case Config_Pulldown:
146 *PORT_PCR |= PORT_PCR_PE;
149 // Do nothing otherwise
159 // Setup GPIO pins for matrix scanning
162 // Register Matrix CLI dictionary
163 CLI_registerDictionary( matrixCLIDict, matrixCLIDictName );
165 info_msg("Columns: ");
166 printHex( Matrix_colsNum );
169 for ( uint8_t pin = 0; pin < Matrix_colsNum; pin++ )
171 Matrix_pin( Matrix_cols[ pin ], Type_StrobeSetup );
176 printHex( Matrix_rowsNum );
179 for ( uint8_t pin = 0; pin < Matrix_rowsNum; pin++ )
181 Matrix_pin( Matrix_rows[ pin ], Type_SenseSetup );
185 info_msg("Max Keys: ");
186 printHex( Matrix_maxKeys );
188 // Clear out Debounce Array
189 for ( uint8_t item = 0; item < Matrix_maxKeys; item++ )
191 Matrix_scanArray[ item ].prevState = KeyState_Off;
192 Matrix_scanArray[ item ].curState = KeyState_Off;
193 Matrix_scanArray[ item ].activeCount = 0;
194 Matrix_scanArray[ item ].inactiveCount = DebounceDivThreshold_define; // Start at 'off' steady state
197 // Clear scan stats counters
202 void Matrix_keyPositionDebug( KeyPosition pos )
204 // Depending on the state, use a different flag + color
208 print("\033[1mO\033[0m");
212 print("\033[1;33mP\033[0m");
216 print("\033[1;32mH\033[0m");
219 case KeyState_Release:
220 print("\033[1;35mR\033[0m");
223 case KeyState_Invalid:
225 print("\033[1;31mI\033[0m");
231 // Scan the matrix for keypresses
232 // NOTE: scanNum should be reset to 0 after a USB send (to reset all the counters)
233 void Matrix_scan( uint16_t scanNum )
235 // Increment stats counters
236 if ( scanNum > matrixMaxScans ) matrixMaxScans = scanNum;
239 matrixPrevScans = matrixCurScans;
247 // For each strobe, scan each of the sense pins
248 for ( uint8_t strobe = 0; strobe < Matrix_colsNum; strobe++ )
251 Matrix_pin( Matrix_cols[ strobe ], Type_StrobeOn );
253 // Scan each of the sense pins
254 for ( uint8_t sense = 0; sense < Matrix_rowsNum; sense++ )
257 uint8_t key = Matrix_colsNum * sense + strobe;
258 KeyState *state = &Matrix_scanArray[ key ];
260 // If first scan, reset state
263 // Set previous state, and reset current state
264 state->prevState = state->curState;
265 state->curState = KeyState_Invalid;
269 // Increment count and right shift opposing count
270 // This means there is a maximum of scan 13 cycles on a perfect off to on transition
271 // (coming from a steady state 0xFFFF off scans)
272 // Somewhat longer with switch bounciness
273 // The advantage of this is that the count is ongoing and never needs to be reset
274 // State still needs to be kept track of to deal with what to send to the Macro module
275 if ( Matrix_pin( Matrix_rows[ sense ], Type_Sense ) )
277 // Only update if not going to wrap around
278 if ( state->activeCount < DebounceDivThreshold_define ) state->activeCount += 1;
279 state->inactiveCount >>= 1;
281 // Signal Not Detected
284 // Only update if not going to wrap around
285 if ( state->inactiveCount < DebounceDivThreshold_define ) state->inactiveCount += 1;
286 state->activeCount >>= 1;
289 // Check for state change if it hasn't been set
290 // Only check if the minimum number of scans has been met
291 // the current state is invalid
292 // and either active or inactive count is over the debounce threshold
293 if ( state->curState == KeyState_Invalid )
295 switch ( state->prevState )
299 if ( state->activeCount > state->inactiveCount )
301 state->curState = KeyState_Hold;
305 state->curState = KeyState_Release;
309 case KeyState_Release:
311 if ( state->activeCount > state->inactiveCount )
313 state->curState = KeyState_Press;
317 state->curState = KeyState_Off;
321 case KeyState_Invalid:
323 erro_print("Matrix scan bug!! Report me!");
327 // Send keystate to macro module
328 Macro_keyState( key, state->curState );
330 // Matrix Debug, only if there is a state change
331 if ( matrixDebugMode && state->curState != state->prevState )
333 // Basic debug output
334 if ( matrixDebugMode == 1 && state->curState == KeyState_Press )
339 // State transition debug output
340 else if ( matrixDebugMode == 2 )
343 Matrix_keyPositionDebug( state->curState );
351 Matrix_pin( Matrix_cols[ strobe ], Type_StrobeOff );
354 // State Table Output Debug
355 if ( matrixDebugStateCounter > 0 )
358 matrixDebugStateCounter--;
360 // Output stats on number of scans being done per USB send
362 info_msg("Max scans: ");
363 printHex( matrixMaxScans );
365 info_msg("Previous scans: ");
366 printHex( matrixPrevScans );
369 // Output current scan number
370 info_msg("Scan Number: ");
374 // Display the state info for each key
375 print("<key>:<previous state><current state> <active count> <inactive count>");
376 for ( uint8_t key = 0; key < Matrix_maxKeys; key++ )
378 // Every 4 keys, put a newline
383 printHex_op( key, 2 );
386 Matrix_keyPositionDebug( Matrix_scanArray[ key ].prevState );
387 Matrix_keyPositionDebug( Matrix_scanArray[ key ].curState );
389 printHex_op( Matrix_scanArray[ key ].activeCount, 4 );
391 printHex_op( Matrix_scanArray[ key ].inactiveCount, 4 );
400 // ----- CLI Command Functions -----
402 void cliFunc_matrixDebug ( char* args )
404 // Parse number from argument
405 // NOTE: Only first argument is used
408 CLI_argumentIsolation( args, &arg1Ptr, &arg2Ptr );
410 // Set the matrix debug flag depending on the argument
411 // If no argument, set to scan code only
412 // If set to T, set to state transition
413 switch ( arg1Ptr[0] )
418 matrixDebugMode = matrixDebugMode != 2 ? 2 : 0;
423 matrixDebugMode = matrixDebugMode != 1 ? 1 : 0;
432 info_msg("Matrix Debug Mode: ");
433 printInt8( matrixDebugMode );
436 void cliFunc_matrixState ( char* args )
438 // Parse number from argument
439 // NOTE: Only first argument is used
442 CLI_argumentIsolation( args, &arg1Ptr, &arg2Ptr );
444 // Default to 1 if no argument is given
445 matrixDebugStateCounter = 1;
447 if ( arg1Ptr[0] != '\0' )
449 matrixDebugStateCounter = (uint16_t)numToInt( arg1Ptr );