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

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