]> git.donarmstrong.com Git - kiibohd-controller.git/blob - Scan/MatrixARM/matrix_scan.c
Changing decToInt to numToInt (adds support for Hex number interpreter)
[kiibohd-controller.git] / Scan / MatrixARM / matrix_scan.c
1 /* Copyright (C) 2014 by Jacob Alexander
2  *
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:
9  *
10  * The above copyright notice and this permission notice shall be included in
11  * all copies or substantial portions of the Software.
12  *
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
19  * THE SOFTWARE.
20  */
21
22 // ----- Includes -----
23
24 // Compiler Includes
25 #include <Lib/ScanLib.h>
26
27 // Project Includes
28 #include <cli.h>
29 #include <led.h>
30 #include <print.h>
31 #include <macro.h>
32
33 // Local Includes
34 #include "matrix_scan.h"
35
36 // Matrix Configuration
37 #include <matrix.h>
38
39
40
41 // ----- Function Declarations -----
42
43 // CLI Functions
44 void cliFunc_matrixDebug( char* args );
45 void cliFunc_matrixState( char* args );
46
47
48
49 // ----- Variables -----
50
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
57 };
58
59 // Debounce Array
60 KeyState Matrix_scanArray[ Matrix_colsNum * Matrix_rowsNum ];
61
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;
65
66 // Matrix State Table Debug Counter - If non-zero display state table after every matrix scan
67 uint16_t matrixDebugStateCounter = 0;
68
69 // Matrix Scan Counters
70 uint16_t matrixMaxScans  = 0;
71 uint16_t matrixCurScans  = 0;
72 uint16_t matrixPrevScans = 0;
73
74
75
76 // ----- Functions -----
77
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 )
82 {
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;
86
87         // Assumes 0x40 between GPIO Port registers and 0x1000 between PORT pin registers
88         // See Lib/mk20dx.h
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;
94
95         // Operation depends on Type
96         switch ( type )
97         {
98         case Type_StrobeOn:
99                 *GPIO_PSOR |= (1 << gpio.pin);
100                 break;
101
102         case Type_StrobeOff:
103                 *GPIO_PCOR |= (1 << gpio.pin);
104                 break;
105
106         case Type_StrobeSetup:
107                 // Set as output pin
108                 *GPIO_PDDR |= (1 << gpio.pin);
109
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);
112
113                 // Enabling open-drain if specified
114                 switch ( Matrix_type )
115                 {
116                 case Config_Opendrain:
117                         *PORT_PCR |= PORT_PCR_ODE;
118                         break;
119
120                 // Do nothing otherwise
121                 default:
122                         break;
123                 }
124                 break;
125
126         case Type_Sense:
127                 return *GPIO_PDIR & (1 << gpio.pin) ? 1 : 0;
128
129         case Type_SenseSetup:
130                 // Set as input pin
131                 *GPIO_PDDR &= ~(1 << gpio.pin);
132
133                 // Configure pin with passive filter and GPIO mux
134                 *PORT_PCR = PORT_PCR_PFE | PORT_PCR_MUX(1);
135
136                 // Pull resistor config
137                 switch ( Matrix_type )
138                 {
139                 case Config_Pullup:
140                         *PORT_PCR |= PORT_PCR_PE | PORT_PCR_PS;
141                         break;
142
143                 case Config_Pulldown:
144                         *PORT_PCR |= PORT_PCR_PE;
145                         break;
146
147                 // Do nothing otherwise
148                 default:
149                         break;
150                 }
151                 break;
152         }
153
154         return 0;
155 }
156
157 // Setup GPIO pins for matrix scanning
158 void Matrix_setup()
159 {
160         // Register Matrix CLI dictionary
161         CLI_registerDictionary( matrixCLIDict, matrixCLIDictName );
162
163         info_msg("Columns:  ");
164         printHex( Matrix_colsNum );
165
166         // Setup Strobe Pins
167         for ( uint8_t pin = 0; pin < Matrix_colsNum; pin++ )
168         {
169                 Matrix_pin( Matrix_cols[ pin ], Type_StrobeSetup );
170         }
171
172         print( NL );
173         info_msg("Rows:     ");
174         printHex( Matrix_rowsNum );
175
176         // Setup Sense Pins
177         for ( uint8_t pin = 0; pin < Matrix_rowsNum; pin++ )
178         {
179                 Matrix_pin( Matrix_rows[ pin ], Type_SenseSetup );
180         }
181
182         print( NL );
183         info_msg("Max Keys: ");
184         printHex( Matrix_maxKeys );
185
186         // Clear out Debounce Array
187         for ( uint8_t item = 0; item < Matrix_maxKeys; item++ )
188         {
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
193         }
194
195         // Clear scan stats counters
196         matrixMaxScans  = 0;
197         matrixPrevScans = 0;
198 }
199
200 void Matrix_keyPositionDebug( KeyPosition pos )
201 {
202         // Depending on the state, use a different flag + color
203         switch ( pos )
204         {
205         case KeyState_Off:
206                 print("\033[1mO\033[0m");
207                 break;
208
209         case KeyState_Press:
210                 print("\033[1;33mP\033[0m");
211                 break;
212
213         case KeyState_Hold:
214                 print("\033[1;32mH\033[0m");
215                 break;
216
217         case KeyState_Release:
218                 print("\033[1;35mR\033[0m");
219                 break;
220
221         case KeyState_Invalid:
222         default:
223                 print("\033[1;31mI\033[0m");
224                 break;
225         }
226 }
227
228
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 )
232 {
233         // Increment stats counters
234         if ( scanNum > matrixMaxScans ) matrixMaxScans = scanNum;
235         if ( scanNum == 0 )
236         {
237                 matrixPrevScans = matrixCurScans;
238                 matrixCurScans = 0;
239         }
240         else
241         {
242                 matrixCurScans++;
243         }
244
245         // For each strobe, scan each of the sense pins
246         for ( uint8_t strobe = 0; strobe < Matrix_colsNum; strobe++ )
247         {
248                 // Strobe Pin
249                 Matrix_pin( Matrix_cols[ strobe ], Type_StrobeOn );
250
251                 // Scan each of the sense pins
252                 for ( uint8_t sense = 0; sense < Matrix_rowsNum; sense++ )
253                 {
254                         // Key position
255                         uint8_t key = Matrix_colsNum * sense + strobe;
256                         KeyState *state = &Matrix_scanArray[ key ];
257
258                         // If first scan, reset state
259                         if ( scanNum == 0 )
260                         {
261                                 // Set previous state, and reset current state
262                                 state->prevState = state->curState;
263                                 state->curState  = KeyState_Invalid;
264                         }
265
266                         // Signal Detected
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 ) )
274                         {
275                                 // Only update if not going to wrap around
276                                 if ( state->activeCount < 0xFFFF ) state->activeCount += 1;
277                                 state->inactiveCount >>= 1;
278                         }
279                         // Signal Not Detected
280                         else
281                         {
282                                 // Only update if not going to wrap around
283                                 if ( state->inactiveCount < 0xFFFF ) state->inactiveCount += 1;
284                                 state->activeCount >>= 1;
285                         }
286
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 )
292                         {
293                                 switch ( state->prevState )
294                                 {
295                                 case KeyState_Press:
296                                 case KeyState_Hold:
297                                         if ( state->activeCount > state->inactiveCount )
298                                         {
299                                                 state->curState = KeyState_Hold;
300                                         }
301                                         else
302                                         {
303                                                 state->curState = KeyState_Release;
304                                         }
305                                         break;
306
307                                 case KeyState_Release:
308                                 case KeyState_Off:
309                                         if ( state->activeCount > state->inactiveCount )
310                                         {
311                                                 state->curState = KeyState_Press;
312                                         }
313                                         else
314                                         {
315                                                 state->curState = KeyState_Off;
316                                         }
317                                         break;
318
319                                 case KeyState_Invalid:
320                                 default:
321                                         erro_print("Matrix scan bug!! Report me!");
322                                         break;
323                                 }
324
325                                 // Send keystate to macro module
326                                 Macro_keyState( key, state->curState );
327
328                                 // Matrix Debug, only if there is a state change
329                                 if ( matrixDebugMode && state->curState != state->prevState )
330                                 {
331                                         // Basic debug output
332                                         if ( matrixDebugMode == 1 && state->curState == KeyState_Press )
333                                         {
334                                                 printHex( key );
335                                                 print(" ");
336                                         }
337                                         // State transition debug output
338                                         else if ( matrixDebugMode == 2 )
339                                         {
340                                                 printHex( key );
341                                                 Matrix_keyPositionDebug( state->curState );
342                                                 print(" ");
343                                         }
344                                 }
345                         }
346                 }
347
348                 // Unstrobe Pin
349                 Matrix_pin( Matrix_cols[ strobe ], Type_StrobeOff );
350         }
351
352         // State Table Output Debug
353         if ( matrixDebugStateCounter > 0 )
354         {
355                 // Decrement counter
356                 matrixDebugStateCounter--;
357
358                 // Output stats on number of scans being done per USB send
359                 print( NL );
360                 info_msg("Max scans:      ");
361                 printHex( matrixMaxScans );
362                 print( NL );
363                 info_msg("Previous scans: ");
364                 printHex( matrixPrevScans );
365                 print( NL );
366
367                 // Output current scan number
368                 info_msg("Scan Number:    ");
369                 printHex( scanNum );
370                 print( NL );
371
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++ )
375                 {
376                         // Every 4 keys, put a newline
377                         if ( key % 4 == 0 )
378                                 print( NL );
379
380                         print("\033[1m0x");
381                         printHex_op( key, 2 );
382                         print("\033[0m");
383                         print(":");
384                         Matrix_keyPositionDebug( Matrix_scanArray[ key ].prevState );
385                         Matrix_keyPositionDebug( Matrix_scanArray[ key ].curState );
386                         print(" 0x");
387                         printHex_op( Matrix_scanArray[ key ].activeCount, 4 );
388                         print(" 0x");
389                         printHex_op( Matrix_scanArray[ key ].inactiveCount, 4 );
390                         print(" ");
391                 }
392
393                 print( NL );
394         }
395 }
396
397
398 // ----- CLI Command Functions -----
399
400 void cliFunc_matrixDebug ( char* args )
401 {
402         // Parse number from argument
403         //  NOTE: Only first argument is used
404         char* arg1Ptr;
405         char* arg2Ptr;
406         CLI_argumentIsolation( args, &arg1Ptr, &arg2Ptr );
407
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] )
412         {
413         // T as argument
414         case 'T':
415         case 't':
416                 matrixDebugMode = matrixDebugMode != 2 ? 2 : 0;
417                 break;
418
419         // No argument
420         case '\0':
421                 matrixDebugMode = matrixDebugMode != 1 ? 1 : 0;
422                 break;
423
424         // Invalid argument
425         default:
426                 return;
427         }
428
429         print( NL );
430         info_msg("Matrix Debug Mode: ");
431         printInt8( matrixDebugMode );
432 }
433
434 void cliFunc_matrixState ( char* args )
435 {
436         // Parse number from argument
437         //  NOTE: Only first argument is used
438         char* arg1Ptr;
439         char* arg2Ptr;
440         CLI_argumentIsolation( args, &arg1Ptr, &arg2Ptr );
441
442         // Default to 1 if no argument is given
443         matrixDebugStateCounter = 1;
444
445         if ( arg1Ptr[0] != '\0' )
446         {
447                 matrixDebugStateCounter = (uint16_t)numToInt( arg1Ptr );
448         }
449 }
450