]> git.donarmstrong.com Git - kiibohd-controller.git/blob - Scan/MatrixARM/matrix_scan.c
bbce1dfae458632a99e4731439b33df510fba990
[kiibohd-controller.git] / Scan / MatrixARM / matrix_scan.c
1 /* Copyright (C) 2014-2016 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_defs.h>
30 #include <led.h>
31 #include <print.h>
32 #include <macro.h>
33 #include <Lib/delay.h>
34
35 // Local Includes
36 #include "matrix_scan.h"
37
38 // Matrix Configuration
39 #include <matrix.h>
40
41
42
43 // ----- Defines -----
44
45 #if ( DebounceThrottleDiv_define > 0 )
46 nat_ptr_t Matrix_divCounter = 0;
47 #endif
48
49
50
51 // ----- Function Declarations -----
52
53 // CLI Functions
54 void cliFunc_matrixDebug( char* args );
55 void cliFunc_matrixState( char* args );
56
57
58
59 // ----- Variables -----
60
61 // Scan Module command dictionary
62 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." );
63 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" );
64
65 CLIDict_Def( matrixCLIDict, "Matrix Module Commands" ) = {
66         CLIDict_Item( matrixDebug ),
67         CLIDict_Item( matrixState ),
68         { 0, 0, 0 } // Null entry for dictionary end
69 };
70
71 // Debounce Array
72 KeyState Matrix_scanArray[ Matrix_colsNum * Matrix_rowsNum ];
73
74 // Ghost Arrays
75 #ifdef GHOSTING_MATRIX
76 KeyGhost Matrix_ghostArray[ Matrix_colsNum * Matrix_rowsNum ];
77
78 uint8_t col_use[Matrix_colsNum], row_use[Matrix_rowsNum];  // used count
79 uint8_t col_ghost[Matrix_colsNum], row_ghost[Matrix_rowsNum];  // marked as having ghost if 1
80 #endif
81
82
83 // Matrix debug flag - If set to 1, for each keypress the scan code is displayed in hex
84 //                     If set to 2, for each key state change, the scan code is displayed along with the state
85 uint8_t matrixDebugMode = 0;
86
87 // Matrix State Table Debug Counter - If non-zero display state table after every matrix scan
88 uint16_t matrixDebugStateCounter = 0;
89
90 // Matrix Scan Counters
91 uint16_t matrixMaxScans  = 0;
92 uint16_t matrixCurScans  = 0;
93 uint16_t matrixPrevScans = 0;
94
95 // System Timer used for delaying debounce decisions
96 extern volatile uint32_t systick_millis_count;
97
98
99
100 // ----- Functions -----
101
102 // Pin action (Strobe, Sense, Strobe Setup, Sense Setup)
103 // NOTE: This function is highly dependent upon the organization of the register map
104 //       Only guaranteed to work with Freescale MK20 series uCs
105 uint8_t Matrix_pin( GPIO_Pin gpio, Type type )
106 {
107         // Register width is defined as size of a pointer
108         unsigned int gpio_offset = gpio.port * 0x40   / sizeof(unsigned int*);
109         unsigned int port_offset = gpio.port * 0x1000 / sizeof(unsigned int*) + gpio.pin;
110
111         // Assumes 0x40 between GPIO Port registers and 0x1000 between PORT pin registers
112         // See Lib/mk20dx.h
113         volatile unsigned int *GPIO_PDDR = (unsigned int*)(&GPIOA_PDDR) + gpio_offset;
114         #ifndef GHOSTING_MATRIX
115         volatile unsigned int *GPIO_PSOR = (unsigned int*)(&GPIOA_PSOR) + gpio_offset;
116         #endif
117         volatile unsigned int *GPIO_PCOR = (unsigned int*)(&GPIOA_PCOR) + gpio_offset;
118         volatile unsigned int *GPIO_PDIR = (unsigned int*)(&GPIOA_PDIR) + gpio_offset;
119         volatile unsigned int *PORT_PCR  = (unsigned int*)(&PORTA_PCR0) + port_offset;
120
121         // Operation depends on Type
122         switch ( type )
123         {
124         case Type_StrobeOn:
125                 #ifdef GHOSTING_MATRIX
126                 *GPIO_PCOR |= (1 << gpio.pin);
127                 *GPIO_PDDR |= (1 << gpio.pin);  // output, low
128                 #else
129                 *GPIO_PSOR |= (1 << gpio.pin);
130                 #endif
131                 break;
132
133         case Type_StrobeOff:
134                 #ifdef GHOSTING_MATRIX
135                 // Ghosting martix needs to put not used (off) strobes in high impedance state
136                 *GPIO_PDDR &= ~(1 << gpio.pin);  // input, high Z state
137                 #endif
138                 *GPIO_PCOR |= (1 << gpio.pin);
139                 break;
140
141         case Type_StrobeSetup:
142                 #ifdef GHOSTING_MATRIX
143                 *GPIO_PDDR &= ~(1 << gpio.pin);  // input, high Z state
144                 *GPIO_PCOR |= (1 << gpio.pin);
145                 #else
146                 // Set as output pin
147                 *GPIO_PDDR |= (1 << gpio.pin);
148                 #endif
149
150                 // Configure pin with slow slew, high drive strength and GPIO mux
151                 *PORT_PCR = PORT_PCR_SRE | PORT_PCR_DSE | PORT_PCR_MUX(1);
152
153                 // Enabling open-drain if specified
154                 switch ( Matrix_type )
155                 {
156                 case Config_Opendrain:
157                         *PORT_PCR |= PORT_PCR_ODE;
158                         break;
159
160                 // Do nothing otherwise
161                 default:
162                         break;
163                 }
164                 break;
165
166         case Type_Sense:
167                 #ifdef GHOSTING_MATRIX  // inverted
168                 return *GPIO_PDIR & (1 << gpio.pin) ? 0 : 1;
169                 #else
170                 return *GPIO_PDIR & (1 << gpio.pin) ? 1 : 0;
171                 #endif
172
173         case Type_SenseSetup:
174                 // Set as input pin
175                 *GPIO_PDDR &= ~(1 << gpio.pin);
176
177                 // Configure pin with passive filter and GPIO mux
178                 *PORT_PCR = PORT_PCR_PFE | PORT_PCR_MUX(1);
179
180                 // Pull resistor config
181                 switch ( Matrix_type )
182                 {
183                 case Config_Pullup:
184                         *PORT_PCR |= PORT_PCR_PE | PORT_PCR_PS;
185                         break;
186
187                 case Config_Pulldown:
188                         *PORT_PCR |= PORT_PCR_PE;
189                         break;
190
191                 // Do nothing otherwise
192                 default:
193                         break;
194                 }
195                 break;
196         }
197
198         return 0;
199 }
200
201 // Setup GPIO pins for matrix scanning
202 void Matrix_setup()
203 {
204         // Register Matrix CLI dictionary
205         CLI_registerDictionary( matrixCLIDict, matrixCLIDictName );
206
207         info_msg("Columns:  ");
208         printHex( Matrix_colsNum );
209
210         // Setup Strobe Pins
211         for ( uint8_t pin = 0; pin < Matrix_colsNum; pin++ )
212         {
213                 Matrix_pin( Matrix_cols[ pin ], Type_StrobeSetup );
214         }
215
216         print( NL );
217         info_msg("Rows:     ");
218         printHex( Matrix_rowsNum );
219
220         // Setup Sense Pins
221         for ( uint8_t pin = 0; pin < Matrix_rowsNum; pin++ )
222         {
223                 Matrix_pin( Matrix_rows[ pin ], Type_SenseSetup );
224         }
225
226         print( NL );
227         info_msg("Max Keys: ");
228         printHex( Matrix_maxKeys );
229         print( NL );
230
231         // Clear out Debounce Array
232         for ( uint8_t item = 0; item < Matrix_maxKeys; item++ )
233         {
234                 Matrix_scanArray[ item ].prevState        = KeyState_Off;
235                 Matrix_scanArray[ item ].curState         = KeyState_Off;
236                 Matrix_scanArray[ item ].activeCount      = 0;
237                 Matrix_scanArray[ item ].inactiveCount    = DebounceDivThreshold_define; // Start at 'off' steady state
238                 Matrix_scanArray[ item ].prevDecisionTime = 0;
239                 #ifdef GHOSTING_MATRIX
240                 Matrix_ghostArray[ item ].prev            = KeyState_Off;
241                 Matrix_ghostArray[ item ].cur             = KeyState_Off;
242                 Matrix_ghostArray[ item ].saved           = KeyState_Off;
243                 #endif
244         }
245
246         // Clear scan stats counters
247         matrixMaxScans  = 0;
248         matrixPrevScans = 0;
249 }
250
251 void Matrix_keyPositionDebug( KeyPosition pos )
252 {
253         // Depending on the state, use a different flag + color
254         switch ( pos )
255         {
256         case KeyState_Off:
257                 print("\033[1mO\033[0m");
258                 break;
259
260         case KeyState_Press:
261                 print("\033[1;33mP\033[0m");
262                 break;
263
264         case KeyState_Hold:
265                 print("\033[1;32mH\033[0m");
266                 break;
267
268         case KeyState_Release:
269                 print("\033[1;35mR\033[0m");
270                 break;
271
272         case KeyState_Invalid:
273         default:
274                 print("\033[1;31mI\033[0m");
275                 break;
276         }
277 }
278
279
280 // Scan the matrix for keypresses
281 // NOTE: scanNum should be reset to 0 after a USB send (to reset all the counters)
282 void Matrix_scan( uint16_t scanNum )
283 {
284 #if ( DebounceThrottleDiv_define > 0 )
285         // Scan-rate throttling
286         // By scanning using a divider, the scan rate slowed down
287         // DebounceThrottleDiv_define == 1 means -> /2 or half scan rate
288         // This helps with bouncy switches on fast uCs
289         if ( !( Matrix_divCounter++ & (1 << ( DebounceThrottleDiv_define - 1 )) ) )
290                 return;
291 #endif
292
293         // Increment stats counters
294         if ( scanNum > matrixMaxScans ) matrixMaxScans = scanNum;
295         if ( scanNum == 0 )
296         {
297                 matrixPrevScans = matrixCurScans;
298                 matrixCurScans = 0;
299         }
300         else
301         {
302                 matrixCurScans++;
303         }
304
305         // Read systick for event scheduling
306         uint8_t currentTime = (uint8_t)systick_millis_count;
307
308         // For each strobe, scan each of the sense pins
309         for ( uint8_t strobe = 0; strobe < Matrix_colsNum; strobe++ )
310         {
311                 #ifdef STROBE_DELAY
312                 uint32_t start = micros();
313                 while ((micros() - start) < STROBE_DELAY);
314                 #endif
315
316                 // Strobe Pin
317                 Matrix_pin( Matrix_cols[ strobe ], Type_StrobeOn );
318
319                 #ifdef STROBE_DELAY
320                 start = micros();
321                 while ((micros() - start) < STROBE_DELAY);
322                 #endif
323
324                 // Scan each of the sense pins
325                 for ( uint8_t sense = 0; sense < Matrix_rowsNum; sense++ )
326                 {
327                         // Key position
328                         uint8_t key = Matrix_colsNum * sense + strobe;
329                         KeyState *state = &Matrix_scanArray[ key ];
330
331                         // If first scan, reset state
332                         if ( scanNum == 0 )
333                         {
334                                 // Set previous state, and reset current state
335                                 state->prevState = state->curState;
336                                 state->curState  = KeyState_Invalid;
337                         }
338
339                         // Signal Detected
340                         // Increment count and right shift opposing count
341                         // This means there is a maximum of scan 13 cycles on a perfect off to on transition
342                         //  (coming from a steady state 0xFFFF off scans)
343                         // Somewhat longer with switch bounciness
344                         // The advantage of this is that the count is ongoing and never needs to be reset
345                         // State still needs to be kept track of to deal with what to send to the Macro module
346                         if ( Matrix_pin( Matrix_rows[ sense ], Type_Sense ) )
347                         {
348                                 // Only update if not going to wrap around
349                                 if ( state->activeCount < DebounceDivThreshold_define ) state->activeCount += 1;
350                                 state->inactiveCount >>= 1;
351                         }
352                         // Signal Not Detected
353                         else
354                         {
355                                 // Only update if not going to wrap around
356                                 if ( state->inactiveCount < DebounceDivThreshold_define ) state->inactiveCount += 1;
357                                 state->activeCount >>= 1;
358                         }
359
360                         // Check for state change if it hasn't been set
361                         // But only if enough time has passed since last state change
362                         // Only check if the minimum number of scans has been met
363                         //   the current state is invalid
364                         //   and either active or inactive count is over the debounce threshold
365                         if ( state->curState == KeyState_Invalid )
366                         {
367                                 // Determine time since last decision
368                                 uint8_t lastTransition = currentTime - state->prevDecisionTime;
369
370                                 // Attempt state transition
371                                 switch ( state->prevState )
372                                 {
373                                 case KeyState_Press:
374                                 case KeyState_Hold:
375                                         if ( state->activeCount > state->inactiveCount )
376                                         {
377                                                 state->curState = KeyState_Hold;
378                                         }
379                                         else
380                                         {
381                                                 // If not enough time has passed since Hold
382                                                 // Keep previous state
383                                                 if ( lastTransition < MinDebounceTime_define )
384                                                 {
385                                                         //warn_print("FAST Release stopped");
386                                                         state->curState = state->prevState;
387                                                         continue;
388                                                 }
389
390                                                 state->curState = KeyState_Release;
391                                         }
392                                         break;
393
394                                 case KeyState_Release:
395                                 case KeyState_Off:
396                                         if ( state->activeCount > state->inactiveCount )
397                                         {
398                                                 // If not enough time has passed since Hold
399                                                 // Keep previous state
400                                                 if ( lastTransition < MinDebounceTime_define )
401                                                 {
402                                                         //warn_print("FAST Press stopped");
403                                                         state->curState = state->prevState;
404                                                         continue;
405                                                 }
406
407                                                 state->curState = KeyState_Press;
408                                         }
409                                         else
410                                         {
411                                                 state->curState = KeyState_Off;
412                                         }
413                                         break;
414
415                                 case KeyState_Invalid:
416                                 default:
417                                         erro_print("Matrix scan bug!! Report me!");
418                                         break;
419                                 }
420
421                                 // Update decision time
422                                 state->prevDecisionTime = currentTime;
423
424                                 // Send keystate to macro module
425                                 #ifndef GHOSTING_MATRIX
426                                 Macro_keyState( key, state->curState );
427                                 #endif
428
429                                 // Matrix Debug, only if there is a state change
430                                 if ( matrixDebugMode && state->curState != state->prevState )
431                                 {
432                                         // Basic debug output
433                                         if ( matrixDebugMode == 1 && state->curState == KeyState_Press )
434                                         {
435                                                 printHex( key );
436                                                 print(" ");
437                                         }
438                                         // State transition debug output
439                                         else if ( matrixDebugMode == 2 )
440                                         {
441                                                 printHex( key );
442                                                 Matrix_keyPositionDebug( state->curState );
443                                                 print(" ");
444                                         }
445                                 }
446                         }
447                 }
448
449                 // Unstrobe Pin
450                 Matrix_pin( Matrix_cols[ strobe ], Type_StrobeOff );
451         }
452
453
454         // Matrix ghosting check and elimination
455         // . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
456 #ifdef GHOSTING_MATRIX
457         // strobe = column, sense = row
458
459         // Count (rows) use for columns
460         //print("C ");
461         for ( uint8_t col = 0; col < Matrix_colsNum; col++ )
462         {
463                 uint8_t used = 0;
464                 for ( uint8_t row = 0; row < Matrix_rowsNum; row++ )
465                 {
466                         uint8_t key = Matrix_colsNum * row + col;
467                         KeyState *state = &Matrix_scanArray[ key ];
468                         if ( keyOn(state->curState) )
469                                 used++;
470                 }
471                 //printInt8(used);
472                 col_use[col] = used;
473                 col_ghost[col] = 0;  // clear
474         }
475
476         // Count (columns) use for rows
477         //print("  R ");
478         for ( uint8_t row = 0; row < Matrix_rowsNum; row++ )
479         {
480                 uint8_t used = 0;
481                 for ( uint8_t col = 0; col < Matrix_colsNum; col++ )
482                 {
483                         uint8_t key = Matrix_colsNum * row + col;
484                         KeyState *state = &Matrix_scanArray[ key ];
485                         if ( keyOn(state->curState) )
486                                 used++;
487                 }
488                 //printInt8(used);
489                 row_use[row] = used;
490                 row_ghost[row] = 0;  // clear
491         }
492
493         // Check if matrix has ghost
494         // Happens when key is pressed and some other key is pressed in same row and another in same column
495         //print("  G ");
496         for ( uint8_t col = 0; col < Matrix_colsNum; col++ )
497         {
498                 for ( uint8_t row = 0; row < Matrix_rowsNum; row++ )
499                 {
500                         uint8_t key = Matrix_colsNum * row + col;
501                         KeyState *state = &Matrix_scanArray[ key ];
502                         if ( keyOn(state->curState) && col_use[col] >= 2 && row_use[row] >= 2 )
503                         {
504                                 // mark col and row as having ghost
505                                 col_ghost[col] = 1;
506                                 row_ghost[row] = 1;
507                                 //print(" ");  printInt8(col);  print(",");  printInt8(row);
508                         }
509                 }
510         }
511         //print( NL );
512
513         // Send keys
514         for ( uint8_t col = 0; col < Matrix_colsNum; col++ )
515         {
516                 for ( uint8_t row = 0; row < Matrix_rowsNum; row++ )
517                 {
518                         uint8_t key = Matrix_colsNum * row + col;
519                         KeyState *state = &Matrix_scanArray[ key ];
520                         KeyGhost *st = &Matrix_ghostArray[ key ];
521
522                         // col or row is ghosting (crossed)
523                         uint8_t ghost = (col_ghost[col] > 0 || row_ghost[row] > 0) ? 1 : 0;
524
525                         st->prev = st->cur;  // previous
526                         // save state if no ghost or outside ghosted area
527                         if ( ghost == 0 )
528                                 st->saved = state->curState;  // save state if no ghost
529                         // final
530                         // use saved state if ghosting, or current if not
531                         st->cur = ghost > 0 ? st->saved : state->curState;
532
533                         //  Send keystate to macro module
534                         KeyPosition k = !st->cur
535                                 ? (!st->prev ? KeyState_Off : KeyState_Release)
536                                 : ( st->prev ? KeyState_Hold : KeyState_Press);
537                         Macro_keyState( key, k );
538                 }
539         }
540 #endif
541         // . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
542
543
544         // State Table Output Debug
545         if ( matrixDebugStateCounter > 0 )
546         {
547                 // Decrement counter
548                 matrixDebugStateCounter--;
549
550                 // Output stats on number of scans being done per USB send
551                 print( NL );
552                 info_msg("Max scans:      ");
553                 printHex( matrixMaxScans );
554                 print( NL );
555                 info_msg("Previous scans: ");
556                 printHex( matrixPrevScans );
557                 print( NL );
558
559                 // Output current scan number
560                 info_msg("Scan Number:    ");
561                 printHex( scanNum );
562                 print( NL );
563
564                 // Display the state info for each key
565                 print("<key>:<previous state><current state> <active count> <inactive count>");
566                 for ( uint8_t key = 0; key < Matrix_maxKeys; key++ )
567                 {
568                         // Every 4 keys, put a newline
569                         if ( key % 4 == 0 )
570                                 print( NL );
571
572                         print("\033[1m0x");
573                         printHex_op( key, 2 );
574                         print("\033[0m");
575                         print(":");
576                         Matrix_keyPositionDebug( Matrix_scanArray[ key ].prevState );
577                         Matrix_keyPositionDebug( Matrix_scanArray[ key ].curState );
578                         print(" 0x");
579                         printHex_op( Matrix_scanArray[ key ].activeCount, 4 );
580                         print(" 0x");
581                         printHex_op( Matrix_scanArray[ key ].inactiveCount, 4 );
582                         print(" ");
583                 }
584
585                 print( NL );
586         }
587 }
588
589
590 // Called by parent scan module whenever the available current changes
591 // current - mA
592 void Matrix_currentChange( unsigned int current )
593 {
594         // TODO - Any potential power savings?
595 }
596
597
598
599 // ----- CLI Command Functions -----
600
601 void cliFunc_matrixDebug ( char* args )
602 {
603         // Parse number from argument
604         //  NOTE: Only first argument is used
605         char* arg1Ptr;
606         char* arg2Ptr;
607         CLI_argumentIsolation( args, &arg1Ptr, &arg2Ptr );
608
609         // Set the matrix debug flag depending on the argument
610         // If no argument, set to scan code only
611         // If set to T, set to state transition
612         switch ( arg1Ptr[0] )
613         {
614         // T as argument
615         case 'T':
616         case 't':
617                 matrixDebugMode = matrixDebugMode != 2 ? 2 : 0;
618                 break;
619
620         // No argument
621         case '\0':
622                 matrixDebugMode = matrixDebugMode != 1 ? 1 : 0;
623                 break;
624
625         // Invalid argument
626         default:
627                 return;
628         }
629
630         print( NL );
631         info_msg("Matrix Debug Mode: ");
632         printInt8( matrixDebugMode );
633 }
634
635 void cliFunc_matrixState ( char* args )
636 {
637         // Parse number from argument
638         //  NOTE: Only first argument is used
639         char* arg1Ptr;
640         char* arg2Ptr;
641         CLI_argumentIsolation( args, &arg1Ptr, &arg2Ptr );
642
643         // Default to 1 if no argument is given
644         matrixDebugStateCounter = 1;
645
646         if ( arg1Ptr[0] != '\0' )
647         {
648                 matrixDebugStateCounter = (uint16_t)numToInt( arg1Ptr );
649         }
650 }
651