1 /* Copyright (C) 2014 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 const char matrixCLIDictName[] = "Matrix Module Commands";
53 const CLIDictItem matrixCLIDict[] = {
54 { "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.", cliFunc_matrixDebug },
55 { "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", cliFunc_matrixState },
56 { 0, 0, 0 } // Null entry for dictionary end
60 KeyState Matrix_scanArray[ Matrix_colsNum * Matrix_rowsNum ];
62 // Matrix debug flag - If set to 1, for each keypress the scan code is displayed in hex
63 // If set to 2, for each key state change, the scan code is displayed along with the state
64 uint8_t matrixDebugMode = 0;
66 // Matrix State Table Debug Counter - If non-zero display state table after every matrix scan
67 uint16_t matrixDebugStateCounter = 0;
69 // Matrix Scan Counters
70 uint16_t matrixMaxScans = 0;
71 uint16_t matrixCurScans = 0;
72 uint16_t matrixPrevScans = 0;
76 // ----- Functions -----
78 // Pin action (Strobe, Sense, Strobe Setup, Sense Setup)
79 // NOTE: This function is highly dependent upon the organization of the register map
80 // Only guaranteed to work with Freescale MK20 series uCs
81 uint8_t Matrix_pin( GPIO_Pin gpio, Type type )
83 // Register width is defined as size of a pointer
84 unsigned int gpio_offset = gpio.port * 0x40 / sizeof(unsigned int*);
85 unsigned int port_offset = gpio.port * 0x1000 / sizeof(unsigned int*) + gpio.pin;
87 // Assumes 0x40 between GPIO Port registers and 0x1000 between PORT pin registers
89 volatile unsigned int *GPIO_PDDR = (unsigned int*)(&GPIOA_PDDR) + gpio_offset;
90 volatile unsigned int *GPIO_PSOR = (unsigned int*)(&GPIOA_PSOR) + gpio_offset;
91 volatile unsigned int *GPIO_PCOR = (unsigned int*)(&GPIOA_PCOR) + gpio_offset;
92 volatile unsigned int *GPIO_PDIR = (unsigned int*)(&GPIOA_PDIR) + gpio_offset;
93 volatile unsigned int *PORT_PCR = (unsigned int*)(&PORTA_PCR0) + port_offset;
95 // Operation depends on Type
99 *GPIO_PSOR |= (1 << gpio.pin);
103 *GPIO_PCOR |= (1 << gpio.pin);
106 case Type_StrobeSetup:
108 *GPIO_PDDR |= (1 << gpio.pin);
110 // Configure pin with slow slew, high drive strength and GPIO mux
111 *PORT_PCR = PORT_PCR_SRE | PORT_PCR_DSE | PORT_PCR_MUX(1);
113 // Enabling open-drain if specified
114 switch ( Matrix_type )
116 case Config_Opendrain:
117 *PORT_PCR |= PORT_PCR_ODE;
120 // Do nothing otherwise
127 return *GPIO_PDIR & (1 << gpio.pin) ? 1 : 0;
129 case Type_SenseSetup:
131 *GPIO_PDDR &= ~(1 << gpio.pin);
133 // Configure pin with passive filter and GPIO mux
134 *PORT_PCR = PORT_PCR_PFE | PORT_PCR_MUX(1);
136 // Pull resistor config
137 switch ( Matrix_type )
140 *PORT_PCR |= PORT_PCR_PE | PORT_PCR_PS;
143 case Config_Pulldown:
144 *PORT_PCR |= PORT_PCR_PE;
147 // Do nothing otherwise
157 // Setup GPIO pins for matrix scanning
160 // Register Matrix CLI dictionary
161 CLI_registerDictionary( matrixCLIDict, matrixCLIDictName );
163 info_msg("Columns: ");
164 printHex( Matrix_colsNum );
167 for ( uint8_t pin = 0; pin < Matrix_colsNum; pin++ )
169 Matrix_pin( Matrix_cols[ pin ], Type_StrobeSetup );
174 printHex( Matrix_rowsNum );
177 for ( uint8_t pin = 0; pin < Matrix_rowsNum; pin++ )
179 Matrix_pin( Matrix_rows[ pin ], Type_SenseSetup );
183 info_msg("Max Keys: ");
184 printHex( Matrix_maxKeys );
186 // Clear out Debounce Array
187 for ( uint8_t item = 0; item < Matrix_maxKeys; item++ )
189 Matrix_scanArray[ item ].prevState = KeyState_Off;
190 Matrix_scanArray[ item ].curState = KeyState_Off;
191 Matrix_scanArray[ item ].activeCount = 0;
192 Matrix_scanArray[ item ].inactiveCount = 0xFFFF; // Start at 'off' steady state
195 // Clear scan stats counters
200 void Matrix_keyPositionDebug( KeyPosition pos )
202 // Depending on the state, use a different flag + color
206 print("\033[1mO\033[0m");
210 print("\033[1;33mP\033[0m");
214 print("\033[1;32mH\033[0m");
217 case KeyState_Release:
218 print("\033[1;35mR\033[0m");
221 case KeyState_Invalid:
223 print("\033[1;31mI\033[0m");
229 // Scan the matrix for keypresses
230 // NOTE: scanNum should be reset to 0 after a USB send (to reset all the counters)
231 void Matrix_scan( uint16_t scanNum )
233 // Increment stats counters
234 if ( scanNum > matrixMaxScans ) matrixMaxScans = scanNum;
237 matrixPrevScans = matrixCurScans;
245 // For each strobe, scan each of the sense pins
246 for ( uint8_t strobe = 0; strobe < Matrix_colsNum; strobe++ )
249 Matrix_pin( Matrix_cols[ strobe ], Type_StrobeOn );
251 // Scan each of the sense pins
252 for ( uint8_t sense = 0; sense < Matrix_rowsNum; sense++ )
255 uint8_t key = Matrix_colsNum * sense + strobe;
256 KeyState *state = &Matrix_scanArray[ key ];
258 // If first scan, reset state
261 // Set previous state, and reset current state
262 state->prevState = state->curState;
263 state->curState = KeyState_Invalid;
267 // Increment count and right shift opposing count
268 // This means there is a maximum of scan 13 cycles on a perfect off to on transition
269 // (coming from a steady state 0xFFFF off scans)
270 // Somewhat longer with switch bounciness
271 // The advantage of this is that the count is ongoing and never needs to be reset
272 // State still needs to be kept track of to deal with what to send to the Macro module
273 if ( Matrix_pin( Matrix_rows[ sense ], Type_Sense ) )
275 // Only update if not going to wrap around
276 if ( state->activeCount < 0xFFFF ) state->activeCount += 1;
277 state->inactiveCount >>= 1;
279 // Signal Not Detected
282 // Only update if not going to wrap around
283 if ( state->inactiveCount < 0xFFFF ) state->inactiveCount += 1;
284 state->activeCount >>= 1;
287 // Check for state change if it hasn't been set
288 // Only check if the minimum number of scans has been met
289 // the current state is invalid
290 // and either active or inactive count is over the debounce threshold
291 if ( state->curState == KeyState_Invalid )
293 switch ( state->prevState )
297 if ( state->activeCount > state->inactiveCount )
299 state->curState = KeyState_Hold;
303 state->curState = KeyState_Release;
307 case KeyState_Release:
309 if ( state->activeCount > state->inactiveCount )
311 state->curState = KeyState_Press;
315 state->curState = KeyState_Off;
319 case KeyState_Invalid:
321 erro_print("Matrix scan bug!! Report me!");
325 // Send keystate to macro module
326 Macro_keyState( key, state->curState );
328 // Matrix Debug, only if there is a state change
329 if ( matrixDebugMode && state->curState != state->prevState )
331 // Basic debug output
332 if ( matrixDebugMode == 1 && state->curState == KeyState_Press )
337 // State transition debug output
338 else if ( matrixDebugMode == 2 )
341 Matrix_keyPositionDebug( state->curState );
349 Matrix_pin( Matrix_cols[ strobe ], Type_StrobeOff );
352 // State Table Output Debug
353 if ( matrixDebugStateCounter > 0 )
356 matrixDebugStateCounter--;
358 // Output stats on number of scans being done per USB send
360 info_msg("Max scans: ");
361 printHex( matrixMaxScans );
363 info_msg("Previous scans: ");
364 printHex( matrixPrevScans );
367 // Output current scan number
368 info_msg("Scan Number: ");
372 // Display the state info for each key
373 print("<key>:<previous state><current state> <active count> <inactive count>");
374 for ( uint8_t key = 0; key < Matrix_maxKeys; key++ )
376 // Every 4 keys, put a newline
381 printHex_op( key, 2 );
384 Matrix_keyPositionDebug( Matrix_scanArray[ key ].prevState );
385 Matrix_keyPositionDebug( Matrix_scanArray[ key ].curState );
387 printHex_op( Matrix_scanArray[ key ].activeCount, 4 );
389 printHex_op( Matrix_scanArray[ key ].inactiveCount, 4 );
398 // ----- CLI Command Functions -----
400 void cliFunc_matrixDebug ( char* args )
402 // Parse number from argument
403 // NOTE: Only first argument is used
406 CLI_argumentIsolation( args, &arg1Ptr, &arg2Ptr );
408 // Set the matrix debug flag depending on the argument
409 // If no argument, set to scan code only
410 // If set to T, set to state transition
411 switch ( arg1Ptr[0] )
416 matrixDebugMode = matrixDebugMode != 2 ? 2 : 0;
421 matrixDebugMode = matrixDebugMode != 1 ? 1 : 0;
430 info_msg("Matrix Debug Mode: ");
431 printInt8( matrixDebugMode );
434 void cliFunc_matrixState ( char* args )
436 // Parse number from argument
437 // NOTE: Only first argument is used
440 CLI_argumentIsolation( args, &arg1Ptr, &arg2Ptr );
442 // Default to 1 if no argument is given
443 matrixDebugStateCounter = 1;
445 if ( arg1Ptr[0] != '\0' )
447 matrixDebugStateCounter = (uint16_t)numToInt( arg1Ptr );