]> git.donarmstrong.com Git - kiibohd-controller.git/blob - Scan/MatrixARM/matrix_scan.c
85f82050f33cb4ef83ce08086af369d85db0ccc0
[kiibohd-controller.git] / Scan / MatrixARM / matrix_scan.c
1 /* Copyright (C) 2014-2015 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 <kll.h>
30 #include <led.h>
31 #include <print.h>
32 #include <macro.h>
33
34 // Local Includes
35 #include "matrix_scan.h"
36
37 // Matrix Configuration
38 #include <matrix.h>
39
40
41
42 // ----- Defines -----
43
44 #if ( DebounceThrottleDiv_define > 0 )
45 nat_ptr_t Matrix_divCounter = 0;
46 #endif
47
48
49
50 // ----- Function Declarations -----
51
52 // CLI Functions
53 void cliFunc_matrixDebug( char* args );
54 void cliFunc_matrixState( char* args );
55
56
57
58 // ----- Variables -----
59
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" );
63
64 CLIDict_Def( matrixCLIDict, "Matrix Module Commands" ) = {
65         CLIDict_Item( matrixDebug ),
66         CLIDict_Item( matrixState ),
67         { 0, 0, 0 } // Null entry for dictionary end
68 };
69
70 // Debounce Array
71 KeyState Matrix_scanArray[ Matrix_colsNum * Matrix_rowsNum ];
72
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;
76
77 // Matrix State Table Debug Counter - If non-zero display state table after every matrix scan
78 uint16_t matrixDebugStateCounter = 0;
79
80 // Matrix Scan Counters
81 uint16_t matrixMaxScans  = 0;
82 uint16_t matrixCurScans  = 0;
83 uint16_t matrixPrevScans = 0;
84
85
86
87 // ----- Functions -----
88
89 // Pin action (Strobe, Sense, Strobe Setup, Sense Setup)
90 // NOTE: This function is highly dependent upon the organization of the register map
91 //       Only guaranteed to work with Freescale MK20 series uCs
92 uint8_t Matrix_pin( GPIO_Pin gpio, Type type )
93 {
94         // Register width is defined as size of a pointer
95         unsigned int gpio_offset = gpio.port * 0x40   / sizeof(unsigned int*);
96         unsigned int port_offset = gpio.port * 0x1000 / sizeof(unsigned int*) + gpio.pin;
97
98         // Assumes 0x40 between GPIO Port registers and 0x1000 between PORT pin registers
99         // See Lib/mk20dx.h
100         volatile unsigned int *GPIO_PDDR = (unsigned int*)(&GPIOA_PDDR) + gpio_offset;
101         volatile unsigned int *GPIO_PSOR = (unsigned int*)(&GPIOA_PSOR) + gpio_offset;
102         volatile unsigned int *GPIO_PCOR = (unsigned int*)(&GPIOA_PCOR) + gpio_offset;
103         volatile unsigned int *GPIO_PDIR = (unsigned int*)(&GPIOA_PDIR) + gpio_offset;
104         volatile unsigned int *PORT_PCR  = (unsigned int*)(&PORTA_PCR0) + port_offset;
105
106         // Operation depends on Type
107         switch ( type )
108         {
109         case Type_StrobeOn:
110                 *GPIO_PSOR |= (1 << gpio.pin);
111                 break;
112
113         case Type_StrobeOff:
114                 *GPIO_PCOR |= (1 << gpio.pin);
115                 break;
116
117         case Type_StrobeSetup:
118                 // Set as output pin
119                 *GPIO_PDDR |= (1 << gpio.pin);
120
121                 // Configure pin with slow slew, high drive strength and GPIO mux
122                 *PORT_PCR = PORT_PCR_SRE | PORT_PCR_DSE | PORT_PCR_MUX(1);
123
124                 // Enabling open-drain if specified
125                 switch ( Matrix_type )
126                 {
127                 case Config_Opendrain:
128                         *PORT_PCR |= PORT_PCR_ODE;
129                         break;
130
131                 // Do nothing otherwise
132                 default:
133                         break;
134                 }
135                 break;
136
137         case Type_Sense:
138                 return *GPIO_PDIR & (1 << gpio.pin) ? 1 : 0;
139
140         case Type_SenseSetup:
141                 // Set as input pin
142                 *GPIO_PDDR &= ~(1 << gpio.pin);
143
144                 // Configure pin with passive filter and GPIO mux
145                 *PORT_PCR = PORT_PCR_PFE | PORT_PCR_MUX(1);
146
147                 // Pull resistor config
148                 switch ( Matrix_type )
149                 {
150                 case Config_Pullup:
151                         *PORT_PCR |= PORT_PCR_PE | PORT_PCR_PS;
152                         break;
153
154                 case Config_Pulldown:
155                         *PORT_PCR |= PORT_PCR_PE;
156                         break;
157
158                 // Do nothing otherwise
159                 default:
160                         break;
161                 }
162                 break;
163         }
164
165         return 0;
166 }
167
168 // Setup GPIO pins for matrix scanning
169 void Matrix_setup()
170 {
171         // Register Matrix CLI dictionary
172         CLI_registerDictionary( matrixCLIDict, matrixCLIDictName );
173
174         info_msg("Columns:  ");
175         printHex( Matrix_colsNum );
176
177         // Setup Strobe Pins
178         for ( uint8_t pin = 0; pin < Matrix_colsNum; pin++ )
179         {
180                 Matrix_pin( Matrix_cols[ pin ], Type_StrobeSetup );
181         }
182
183         print( NL );
184         info_msg("Rows:     ");
185         printHex( Matrix_rowsNum );
186
187         // Setup Sense Pins
188         for ( uint8_t pin = 0; pin < Matrix_rowsNum; pin++ )
189         {
190                 Matrix_pin( Matrix_rows[ pin ], Type_SenseSetup );
191         }
192
193         print( NL );
194         info_msg("Max Keys: ");
195         printHex( Matrix_maxKeys );
196
197         // Clear out Debounce Array
198         for ( uint8_t item = 0; item < Matrix_maxKeys; item++ )
199         {
200                 Matrix_scanArray[ item ].prevState     = KeyState_Off;
201                 Matrix_scanArray[ item ].curState      = KeyState_Off;
202                 Matrix_scanArray[ item ].activeCount   = 0;
203                 Matrix_scanArray[ item ].inactiveCount = DebounceDivThreshold_define; // Start at 'off' steady state
204         }
205
206         // Clear scan stats counters
207         matrixMaxScans  = 0;
208         matrixPrevScans = 0;
209 }
210
211 void Matrix_keyPositionDebug( KeyPosition pos )
212 {
213         // Depending on the state, use a different flag + color
214         switch ( pos )
215         {
216         case KeyState_Off:
217                 print("\033[1mO\033[0m");
218                 break;
219
220         case KeyState_Press:
221                 print("\033[1;33mP\033[0m");
222                 break;
223
224         case KeyState_Hold:
225                 print("\033[1;32mH\033[0m");
226                 break;
227
228         case KeyState_Release:
229                 print("\033[1;35mR\033[0m");
230                 break;
231
232         case KeyState_Invalid:
233         default:
234                 print("\033[1;31mI\033[0m");
235                 break;
236         }
237 }
238
239
240 // Scan the matrix for keypresses
241 // NOTE: scanNum should be reset to 0 after a USB send (to reset all the counters)
242 void Matrix_scan( uint16_t scanNum )
243 {
244 #if ( DebounceThrottleDiv_define > 0 )
245         // Scan-rate throttling
246         // By scanning using a divider, the scan rate slowed down
247         // DebounceThrottleDiv_define == 1 means -> /2 or half scan rate
248         // This helps with bouncy switches on fast uCs
249         if ( !( Matrix_divCounter++ & (1 << ( DebounceThrottleDiv_define - 1 )) ) )
250                 return;
251 #endif
252
253         // Increment stats counters
254         if ( scanNum > matrixMaxScans ) matrixMaxScans = scanNum;
255         if ( scanNum == 0 )
256         {
257                 matrixPrevScans = matrixCurScans;
258                 matrixCurScans = 0;
259         }
260         else
261         {
262                 matrixCurScans++;
263         }
264
265         // For each strobe, scan each of the sense pins
266         for ( uint8_t strobe = 0; strobe < Matrix_colsNum; strobe++ )
267         {
268                 // Strobe Pin
269                 Matrix_pin( Matrix_cols[ strobe ], Type_StrobeOn );
270
271                 // Scan each of the sense pins
272                 for ( uint8_t sense = 0; sense < Matrix_rowsNum; sense++ )
273                 {
274                         // Key position
275                         uint8_t key = Matrix_colsNum * sense + strobe;
276                         KeyState *state = &Matrix_scanArray[ key ];
277
278                         // If first scan, reset state
279                         if ( scanNum == 0 )
280                         {
281                                 // Set previous state, and reset current state
282                                 state->prevState = state->curState;
283                                 state->curState  = KeyState_Invalid;
284                         }
285
286                         // Signal Detected
287                         // Increment count and right shift opposing count
288                         // This means there is a maximum of scan 13 cycles on a perfect off to on transition
289                         //  (coming from a steady state 0xFFFF off scans)
290                         // Somewhat longer with switch bounciness
291                         // The advantage of this is that the count is ongoing and never needs to be reset
292                         // State still needs to be kept track of to deal with what to send to the Macro module
293                         if ( Matrix_pin( Matrix_rows[ sense ], Type_Sense ) )
294                         {
295                                 // Only update if not going to wrap around
296                                 if ( state->activeCount < DebounceDivThreshold_define ) state->activeCount += 1;
297                                 state->inactiveCount >>= 1;
298                         }
299                         // Signal Not Detected
300                         else
301                         {
302                                 // Only update if not going to wrap around
303                                 if ( state->inactiveCount < DebounceDivThreshold_define ) state->inactiveCount += 1;
304                                 state->activeCount >>= 1;
305                         }
306
307                         // Check for state change if it hasn't been set
308                         // Only check if the minimum number of scans has been met
309                         //   the current state is invalid
310                         //   and either active or inactive count is over the debounce threshold
311                         if ( state->curState == KeyState_Invalid )
312                         {
313                                 switch ( state->prevState )
314                                 {
315                                 case KeyState_Press:
316                                 case KeyState_Hold:
317                                         if ( state->activeCount > state->inactiveCount )
318                                         {
319                                                 state->curState = KeyState_Hold;
320                                         }
321                                         else
322                                         {
323                                                 state->curState = KeyState_Release;
324                                         }
325                                         break;
326
327                                 case KeyState_Release:
328                                 case KeyState_Off:
329                                         if ( state->activeCount > state->inactiveCount )
330                                         {
331                                                 state->curState = KeyState_Press;
332                                         }
333                                         else
334                                         {
335                                                 state->curState = KeyState_Off;
336                                         }
337                                         break;
338
339                                 case KeyState_Invalid:
340                                 default:
341                                         erro_print("Matrix scan bug!! Report me!");
342                                         break;
343                                 }
344
345                                 // Send keystate to macro module
346                                 Macro_keyState( key, state->curState );
347
348                                 // Matrix Debug, only if there is a state change
349                                 if ( matrixDebugMode && state->curState != state->prevState )
350                                 {
351                                         // Basic debug output
352                                         if ( matrixDebugMode == 1 && state->curState == KeyState_Press )
353                                         {
354                                                 printHex( key );
355                                                 print(" ");
356                                         }
357                                         // State transition debug output
358                                         else if ( matrixDebugMode == 2 )
359                                         {
360                                                 printHex( key );
361                                                 Matrix_keyPositionDebug( state->curState );
362                                                 print(" ");
363                                         }
364                                 }
365                         }
366                 }
367
368                 // Unstrobe Pin
369                 Matrix_pin( Matrix_cols[ strobe ], Type_StrobeOff );
370         }
371
372         // State Table Output Debug
373         if ( matrixDebugStateCounter > 0 )
374         {
375                 // Decrement counter
376                 matrixDebugStateCounter--;
377
378                 // Output stats on number of scans being done per USB send
379                 print( NL );
380                 info_msg("Max scans:      ");
381                 printHex( matrixMaxScans );
382                 print( NL );
383                 info_msg("Previous scans: ");
384                 printHex( matrixPrevScans );
385                 print( NL );
386
387                 // Output current scan number
388                 info_msg("Scan Number:    ");
389                 printHex( scanNum );
390                 print( NL );
391
392                 // Display the state info for each key
393                 print("<key>:<previous state><current state> <active count> <inactive count>");
394                 for ( uint8_t key = 0; key < Matrix_maxKeys; key++ )
395                 {
396                         // Every 4 keys, put a newline
397                         if ( key % 4 == 0 )
398                                 print( NL );
399
400                         print("\033[1m0x");
401                         printHex_op( key, 2 );
402                         print("\033[0m");
403                         print(":");
404                         Matrix_keyPositionDebug( Matrix_scanArray[ key ].prevState );
405                         Matrix_keyPositionDebug( Matrix_scanArray[ key ].curState );
406                         print(" 0x");
407                         printHex_op( Matrix_scanArray[ key ].activeCount, 4 );
408                         print(" 0x");
409                         printHex_op( Matrix_scanArray[ key ].inactiveCount, 4 );
410                         print(" ");
411                 }
412
413                 print( NL );
414         }
415 }
416
417
418 // ----- CLI Command Functions -----
419
420 void cliFunc_matrixDebug ( char* args )
421 {
422         // Parse number from argument
423         //  NOTE: Only first argument is used
424         char* arg1Ptr;
425         char* arg2Ptr;
426         CLI_argumentIsolation( args, &arg1Ptr, &arg2Ptr );
427
428         // Set the matrix debug flag depending on the argument
429         // If no argument, set to scan code only
430         // If set to T, set to state transition
431         switch ( arg1Ptr[0] )
432         {
433         // T as argument
434         case 'T':
435         case 't':
436                 matrixDebugMode = matrixDebugMode != 2 ? 2 : 0;
437                 break;
438
439         // No argument
440         case '\0':
441                 matrixDebugMode = matrixDebugMode != 1 ? 1 : 0;
442                 break;
443
444         // Invalid argument
445         default:
446                 return;
447         }
448
449         print( NL );
450         info_msg("Matrix Debug Mode: ");
451         printInt8( matrixDebugMode );
452 }
453
454 void cliFunc_matrixState ( char* args )
455 {
456         // Parse number from argument
457         //  NOTE: Only first argument is used
458         char* arg1Ptr;
459         char* arg2Ptr;
460         CLI_argumentIsolation( args, &arg1Ptr, &arg2Ptr );
461
462         // Default to 1 if no argument is given
463         matrixDebugStateCounter = 1;
464
465         if ( arg1Ptr[0] != '\0' )
466         {
467                 matrixDebugStateCounter = (uint16_t)numToInt( arg1Ptr );
468         }
469 }
470