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