Kiibohd Controller
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
This repo is archived. You can view files and clone it, but cannot push or open issues/pull-requests.

matrix_scan.c 17KB

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