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 13KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504
  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. // 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. // Matrix debug flag - If set to 1, for each keypress the scan code is displayed in hex
  54. // If set to 2, for each key state change, the scan code is displayed along with the state
  55. uint8_t matrixDebugMode = 0;
  56. // Matrix State Table Debug Counter - If non-zero display state table after every matrix scan
  57. uint16_t matrixDebugStateCounter = 0;
  58. // Matrix Scan Counters
  59. uint16_t matrixMaxScans = 0;
  60. uint16_t matrixCurScans = 0;
  61. uint16_t matrixPrevScans = 0;
  62. // System Timer used for delaying debounce decisions
  63. extern volatile uint32_t systick_millis_count;
  64. // ----- Functions -----
  65. // Pin action (Strobe, Sense, Strobe Setup, Sense Setup)
  66. // NOTE: This function is highly dependent upon the organization of the register map
  67. // Only guaranteed to work with Freescale MK20 series uCs
  68. uint8_t Matrix_pin( GPIO_Pin gpio, Type type )
  69. {
  70. // Register width is defined as size of a pointer
  71. unsigned int gpio_offset = gpio.port * 0x40 / sizeof(unsigned int*);
  72. unsigned int port_offset = gpio.port * 0x1000 / sizeof(unsigned int*) + gpio.pin;
  73. // Assumes 0x40 between GPIO Port registers and 0x1000 between PORT pin registers
  74. // See Lib/mk20dx.h
  75. volatile unsigned int *GPIO_PDDR = (unsigned int*)(&GPIOA_PDDR) + gpio_offset;
  76. volatile unsigned int *GPIO_PSOR = (unsigned int*)(&GPIOA_PSOR) + gpio_offset;
  77. volatile unsigned int *GPIO_PCOR = (unsigned int*)(&GPIOA_PCOR) + gpio_offset;
  78. volatile unsigned int *GPIO_PDIR = (unsigned int*)(&GPIOA_PDIR) + gpio_offset;
  79. volatile unsigned int *PORT_PCR = (unsigned int*)(&PORTA_PCR0) + port_offset;
  80. // Operation depends on Type
  81. switch ( type )
  82. {
  83. case Type_StrobeOn:
  84. *GPIO_PSOR |= (1 << gpio.pin);
  85. break;
  86. case Type_StrobeOff:
  87. *GPIO_PCOR |= (1 << gpio.pin);
  88. break;
  89. case Type_StrobeSetup:
  90. // Set as output pin
  91. *GPIO_PDDR |= (1 << gpio.pin);
  92. // Configure pin with slow slew, high drive strength and GPIO mux
  93. *PORT_PCR = PORT_PCR_SRE | PORT_PCR_DSE | PORT_PCR_MUX(1);
  94. // Enabling open-drain if specified
  95. switch ( Matrix_type )
  96. {
  97. case Config_Opendrain:
  98. *PORT_PCR |= PORT_PCR_ODE;
  99. break;
  100. // Do nothing otherwise
  101. default:
  102. break;
  103. }
  104. break;
  105. case Type_Sense:
  106. return *GPIO_PDIR & (1 << gpio.pin) ? 1 : 0;
  107. case Type_SenseSetup:
  108. // Set as input pin
  109. *GPIO_PDDR &= ~(1 << gpio.pin);
  110. // Configure pin with passive filter and GPIO mux
  111. *PORT_PCR = PORT_PCR_PFE | PORT_PCR_MUX(1);
  112. // Pull resistor config
  113. switch ( Matrix_type )
  114. {
  115. case Config_Pullup:
  116. *PORT_PCR |= PORT_PCR_PE | PORT_PCR_PS;
  117. break;
  118. case Config_Pulldown:
  119. *PORT_PCR |= PORT_PCR_PE;
  120. break;
  121. // Do nothing otherwise
  122. default:
  123. break;
  124. }
  125. break;
  126. }
  127. return 0;
  128. }
  129. // Setup GPIO pins for matrix scanning
  130. void Matrix_setup()
  131. {
  132. // Register Matrix CLI dictionary
  133. CLI_registerDictionary( matrixCLIDict, matrixCLIDictName );
  134. info_msg("Columns: ");
  135. printHex( Matrix_colsNum );
  136. // Setup Strobe Pins
  137. for ( uint8_t pin = 0; pin < Matrix_colsNum; pin++ )
  138. {
  139. Matrix_pin( Matrix_cols[ pin ], Type_StrobeSetup );
  140. }
  141. print( NL );
  142. info_msg("Rows: ");
  143. printHex( Matrix_rowsNum );
  144. // Setup Sense Pins
  145. for ( uint8_t pin = 0; pin < Matrix_rowsNum; pin++ )
  146. {
  147. Matrix_pin( Matrix_rows[ pin ], Type_SenseSetup );
  148. }
  149. print( NL );
  150. info_msg("Max Keys: ");
  151. printHex( Matrix_maxKeys );
  152. print( NL );
  153. // Clear out Debounce Array
  154. for ( uint8_t item = 0; item < Matrix_maxKeys; item++ )
  155. {
  156. Matrix_scanArray[ item ].prevState = KeyState_Off;
  157. Matrix_scanArray[ item ].curState = KeyState_Off;
  158. Matrix_scanArray[ item ].activeCount = 0;
  159. Matrix_scanArray[ item ].inactiveCount = DebounceDivThreshold_define; // Start at 'off' steady state
  160. Matrix_scanArray[ item ].prevDecisionTime = 0;
  161. }
  162. // Clear scan stats counters
  163. matrixMaxScans = 0;
  164. matrixPrevScans = 0;
  165. }
  166. void Matrix_keyPositionDebug( KeyPosition pos )
  167. {
  168. // Depending on the state, use a different flag + color
  169. switch ( pos )
  170. {
  171. case KeyState_Off:
  172. print("\033[1mO\033[0m");
  173. break;
  174. case KeyState_Press:
  175. print("\033[1;33mP\033[0m");
  176. break;
  177. case KeyState_Hold:
  178. print("\033[1;32mH\033[0m");
  179. break;
  180. case KeyState_Release:
  181. print("\033[1;35mR\033[0m");
  182. break;
  183. case KeyState_Invalid:
  184. default:
  185. print("\033[1;31mI\033[0m");
  186. break;
  187. }
  188. }
  189. // Scan the matrix for keypresses
  190. // NOTE: scanNum should be reset to 0 after a USB send (to reset all the counters)
  191. void Matrix_scan( uint16_t scanNum )
  192. {
  193. #if ( DebounceThrottleDiv_define > 0 )
  194. // Scan-rate throttling
  195. // By scanning using a divider, the scan rate slowed down
  196. // DebounceThrottleDiv_define == 1 means -> /2 or half scan rate
  197. // This helps with bouncy switches on fast uCs
  198. if ( !( Matrix_divCounter++ & (1 << ( DebounceThrottleDiv_define - 1 )) ) )
  199. return;
  200. #endif
  201. // Increment stats counters
  202. if ( scanNum > matrixMaxScans ) matrixMaxScans = scanNum;
  203. if ( scanNum == 0 )
  204. {
  205. matrixPrevScans = matrixCurScans;
  206. matrixCurScans = 0;
  207. }
  208. else
  209. {
  210. matrixCurScans++;
  211. }
  212. // Read systick for event scheduling
  213. uint8_t currentTime = (uint8_t)systick_millis_count;
  214. // For each strobe, scan each of the sense pins
  215. for ( uint8_t strobe = 0; strobe < Matrix_colsNum; strobe++ )
  216. {
  217. // Strobe Pin
  218. Matrix_pin( Matrix_cols[ strobe ], Type_StrobeOn );
  219. // Scan each of the sense pins
  220. for ( uint8_t sense = 0; sense < Matrix_rowsNum; sense++ )
  221. {
  222. // Key position
  223. uint8_t key = Matrix_colsNum * sense + strobe;
  224. KeyState *state = &Matrix_scanArray[ key ];
  225. // If first scan, reset state
  226. if ( scanNum == 0 )
  227. {
  228. // Set previous state, and reset current state
  229. state->prevState = state->curState;
  230. state->curState = KeyState_Invalid;
  231. }
  232. // Signal Detected
  233. // Increment count and right shift opposing count
  234. // This means there is a maximum of scan 13 cycles on a perfect off to on transition
  235. // (coming from a steady state 0xFFFF off scans)
  236. // Somewhat longer with switch bounciness
  237. // The advantage of this is that the count is ongoing and never needs to be reset
  238. // State still needs to be kept track of to deal with what to send to the Macro module
  239. if ( Matrix_pin( Matrix_rows[ sense ], Type_Sense ) )
  240. {
  241. // Only update if not going to wrap around
  242. if ( state->activeCount < DebounceDivThreshold_define ) state->activeCount += 1;
  243. state->inactiveCount >>= 1;
  244. }
  245. // Signal Not Detected
  246. else
  247. {
  248. // Only update if not going to wrap around
  249. if ( state->inactiveCount < DebounceDivThreshold_define ) state->inactiveCount += 1;
  250. state->activeCount >>= 1;
  251. }
  252. // Check for state change if it hasn't been set
  253. // But only if enough time has passed since last state change
  254. // Only check if the minimum number of scans has been met
  255. // the current state is invalid
  256. // and either active or inactive count is over the debounce threshold
  257. if ( state->curState == KeyState_Invalid )
  258. {
  259. // Determine time since last decision
  260. uint8_t lastTransition = currentTime - state->prevDecisionTime;
  261. // Attempt state transition
  262. switch ( state->prevState )
  263. {
  264. case KeyState_Press:
  265. case KeyState_Hold:
  266. if ( state->activeCount > state->inactiveCount )
  267. {
  268. state->curState = KeyState_Hold;
  269. }
  270. else
  271. {
  272. // If not enough time has passed since Hold
  273. // Keep previous state
  274. if ( lastTransition < MinDebounceTime_define )
  275. {
  276. //warn_print("FAST Release stopped");
  277. state->curState = state->prevState;
  278. continue;
  279. }
  280. state->curState = KeyState_Release;
  281. }
  282. break;
  283. case KeyState_Release:
  284. case KeyState_Off:
  285. if ( state->activeCount > state->inactiveCount )
  286. {
  287. // If not enough time has passed since Hold
  288. // Keep previous state
  289. if ( lastTransition < MinDebounceTime_define )
  290. {
  291. //warn_print("FAST Press stopped");
  292. state->curState = state->prevState;
  293. continue;
  294. }
  295. state->curState = KeyState_Press;
  296. }
  297. else
  298. {
  299. state->curState = KeyState_Off;
  300. }
  301. break;
  302. case KeyState_Invalid:
  303. default:
  304. erro_print("Matrix scan bug!! Report me!");
  305. break;
  306. }
  307. // Update decision time
  308. state->prevDecisionTime = currentTime;
  309. // Send keystate to macro module
  310. Macro_keyState( key, state->curState );
  311. // Matrix Debug, only if there is a state change
  312. if ( matrixDebugMode && state->curState != state->prevState )
  313. {
  314. // Basic debug output
  315. if ( matrixDebugMode == 1 && state->curState == KeyState_Press )
  316. {
  317. printHex( key );
  318. print(" ");
  319. }
  320. // State transition debug output
  321. else if ( matrixDebugMode == 2 )
  322. {
  323. printHex( key );
  324. Matrix_keyPositionDebug( state->curState );
  325. print(" ");
  326. }
  327. }
  328. }
  329. }
  330. // Unstrobe Pin
  331. Matrix_pin( Matrix_cols[ strobe ], Type_StrobeOff );
  332. }
  333. // State Table Output Debug
  334. if ( matrixDebugStateCounter > 0 )
  335. {
  336. // Decrement counter
  337. matrixDebugStateCounter--;
  338. // Output stats on number of scans being done per USB send
  339. print( NL );
  340. info_msg("Max scans: ");
  341. printHex( matrixMaxScans );
  342. print( NL );
  343. info_msg("Previous scans: ");
  344. printHex( matrixPrevScans );
  345. print( NL );
  346. // Output current scan number
  347. info_msg("Scan Number: ");
  348. printHex( scanNum );
  349. print( NL );
  350. // Display the state info for each key
  351. print("<key>:<previous state><current state> <active count> <inactive count>");
  352. for ( uint8_t key = 0; key < Matrix_maxKeys; key++ )
  353. {
  354. // Every 4 keys, put a newline
  355. if ( key % 4 == 0 )
  356. print( NL );
  357. print("\033[1m0x");
  358. printHex_op( key, 2 );
  359. print("\033[0m");
  360. print(":");
  361. Matrix_keyPositionDebug( Matrix_scanArray[ key ].prevState );
  362. Matrix_keyPositionDebug( Matrix_scanArray[ key ].curState );
  363. print(" 0x");
  364. printHex_op( Matrix_scanArray[ key ].activeCount, 4 );
  365. print(" 0x");
  366. printHex_op( Matrix_scanArray[ key ].inactiveCount, 4 );
  367. print(" ");
  368. }
  369. print( NL );
  370. }
  371. }
  372. // ----- CLI Command Functions -----
  373. void cliFunc_matrixDebug ( char* args )
  374. {
  375. // Parse number from argument
  376. // NOTE: Only first argument is used
  377. char* arg1Ptr;
  378. char* arg2Ptr;
  379. CLI_argumentIsolation( args, &arg1Ptr, &arg2Ptr );
  380. // Set the matrix debug flag depending on the argument
  381. // If no argument, set to scan code only
  382. // If set to T, set to state transition
  383. switch ( arg1Ptr[0] )
  384. {
  385. // T as argument
  386. case 'T':
  387. case 't':
  388. matrixDebugMode = matrixDebugMode != 2 ? 2 : 0;
  389. break;
  390. // No argument
  391. case '\0':
  392. matrixDebugMode = matrixDebugMode != 1 ? 1 : 0;
  393. break;
  394. // Invalid argument
  395. default:
  396. return;
  397. }
  398. print( NL );
  399. info_msg("Matrix Debug Mode: ");
  400. printInt8( matrixDebugMode );
  401. }
  402. void cliFunc_matrixState ( char* args )
  403. {
  404. // Parse number from argument
  405. // NOTE: Only first argument is used
  406. char* arg1Ptr;
  407. char* arg2Ptr;
  408. CLI_argumentIsolation( args, &arg1Ptr, &arg2Ptr );
  409. // Default to 1 if no argument is given
  410. matrixDebugStateCounter = 1;
  411. if ( arg1Ptr[0] != '\0' )
  412. {
  413. matrixDebugStateCounter = (uint16_t)numToInt( arg1Ptr );
  414. }
  415. }