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