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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503
  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. // Clear out Debounce Array
  153. for ( uint8_t item = 0; item < Matrix_maxKeys; item++ )
  154. {
  155. Matrix_scanArray[ item ].prevState = KeyState_Off;
  156. Matrix_scanArray[ item ].curState = KeyState_Off;
  157. Matrix_scanArray[ item ].activeCount = 0;
  158. Matrix_scanArray[ item ].inactiveCount = DebounceDivThreshold_define; // Start at 'off' steady state
  159. Matrix_scanArray[ item ].prevDecisionTime = 0;
  160. }
  161. // Clear scan stats counters
  162. matrixMaxScans = 0;
  163. matrixPrevScans = 0;
  164. }
  165. void Matrix_keyPositionDebug( KeyPosition pos )
  166. {
  167. // Depending on the state, use a different flag + color
  168. switch ( pos )
  169. {
  170. case KeyState_Off:
  171. print("\033[1mO\033[0m");
  172. break;
  173. case KeyState_Press:
  174. print("\033[1;33mP\033[0m");
  175. break;
  176. case KeyState_Hold:
  177. print("\033[1;32mH\033[0m");
  178. break;
  179. case KeyState_Release:
  180. print("\033[1;35mR\033[0m");
  181. break;
  182. case KeyState_Invalid:
  183. default:
  184. print("\033[1;31mI\033[0m");
  185. break;
  186. }
  187. }
  188. // Scan the matrix for keypresses
  189. // NOTE: scanNum should be reset to 0 after a USB send (to reset all the counters)
  190. void Matrix_scan( uint16_t scanNum )
  191. {
  192. #if ( DebounceThrottleDiv_define > 0 )
  193. // Scan-rate throttling
  194. // By scanning using a divider, the scan rate slowed down
  195. // DebounceThrottleDiv_define == 1 means -> /2 or half scan rate
  196. // This helps with bouncy switches on fast uCs
  197. if ( !( Matrix_divCounter++ & (1 << ( DebounceThrottleDiv_define - 1 )) ) )
  198. return;
  199. #endif
  200. // Increment stats counters
  201. if ( scanNum > matrixMaxScans ) matrixMaxScans = scanNum;
  202. if ( scanNum == 0 )
  203. {
  204. matrixPrevScans = matrixCurScans;
  205. matrixCurScans = 0;
  206. }
  207. else
  208. {
  209. matrixCurScans++;
  210. }
  211. // Read systick for event scheduling
  212. uint8_t currentTime = (uint8_t)systick_millis_count;
  213. // For each strobe, scan each of the sense pins
  214. for ( uint8_t strobe = 0; strobe < Matrix_colsNum; strobe++ )
  215. {
  216. // Strobe Pin
  217. Matrix_pin( Matrix_cols[ strobe ], Type_StrobeOn );
  218. // Scan each of the sense pins
  219. for ( uint8_t sense = 0; sense < Matrix_rowsNum; sense++ )
  220. {
  221. // Key position
  222. uint8_t key = Matrix_colsNum * sense + strobe;
  223. KeyState *state = &Matrix_scanArray[ key ];
  224. // If first scan, reset state
  225. if ( scanNum == 0 )
  226. {
  227. // Set previous state, and reset current state
  228. state->prevState = state->curState;
  229. state->curState = KeyState_Invalid;
  230. }
  231. // Signal Detected
  232. // Increment count and right shift opposing count
  233. // This means there is a maximum of scan 13 cycles on a perfect off to on transition
  234. // (coming from a steady state 0xFFFF off scans)
  235. // Somewhat longer with switch bounciness
  236. // The advantage of this is that the count is ongoing and never needs to be reset
  237. // State still needs to be kept track of to deal with what to send to the Macro module
  238. if ( Matrix_pin( Matrix_rows[ sense ], Type_Sense ) )
  239. {
  240. // Only update if not going to wrap around
  241. if ( state->activeCount < DebounceDivThreshold_define ) state->activeCount += 1;
  242. state->inactiveCount >>= 1;
  243. }
  244. // Signal Not Detected
  245. else
  246. {
  247. // Only update if not going to wrap around
  248. if ( state->inactiveCount < DebounceDivThreshold_define ) state->inactiveCount += 1;
  249. state->activeCount >>= 1;
  250. }
  251. // Check for state change if it hasn't been set
  252. // But only if enough time has passed since last state change
  253. // Only check if the minimum number of scans has been met
  254. // the current state is invalid
  255. // and either active or inactive count is over the debounce threshold
  256. if ( state->curState == KeyState_Invalid )
  257. {
  258. // Determine time since last decision
  259. uint8_t lastTransition = currentTime - state->prevDecisionTime;
  260. // Attempt state transition
  261. switch ( state->prevState )
  262. {
  263. case KeyState_Press:
  264. case KeyState_Hold:
  265. if ( state->activeCount > state->inactiveCount )
  266. {
  267. state->curState = KeyState_Hold;
  268. }
  269. else
  270. {
  271. // If not enough time has passed since Hold
  272. // Keep previous state
  273. if ( lastTransition < MinDebounceTime_define )
  274. {
  275. //warn_print("FAST Release stopped");
  276. state->curState = state->prevState;
  277. continue;
  278. }
  279. state->curState = KeyState_Release;
  280. }
  281. break;
  282. case KeyState_Release:
  283. case KeyState_Off:
  284. if ( state->activeCount > state->inactiveCount )
  285. {
  286. // If not enough time has passed since Hold
  287. // Keep previous state
  288. if ( lastTransition < MinDebounceTime_define )
  289. {
  290. //warn_print("FAST Press stopped");
  291. state->curState = state->prevState;
  292. continue;
  293. }
  294. state->curState = KeyState_Press;
  295. }
  296. else
  297. {
  298. state->curState = KeyState_Off;
  299. }
  300. break;
  301. case KeyState_Invalid:
  302. default:
  303. erro_print("Matrix scan bug!! Report me!");
  304. break;
  305. }
  306. // Update decision time
  307. state->prevDecisionTime = currentTime;
  308. // Send keystate to macro module
  309. Macro_keyState( key, state->curState );
  310. // Matrix Debug, only if there is a state change
  311. if ( matrixDebugMode && state->curState != state->prevState )
  312. {
  313. // Basic debug output
  314. if ( matrixDebugMode == 1 && state->curState == KeyState_Press )
  315. {
  316. printHex( key );
  317. print(" ");
  318. }
  319. // State transition debug output
  320. else if ( matrixDebugMode == 2 )
  321. {
  322. printHex( key );
  323. Matrix_keyPositionDebug( state->curState );
  324. print(" ");
  325. }
  326. }
  327. }
  328. }
  329. // Unstrobe Pin
  330. Matrix_pin( Matrix_cols[ strobe ], Type_StrobeOff );
  331. }
  332. // State Table Output Debug
  333. if ( matrixDebugStateCounter > 0 )
  334. {
  335. // Decrement counter
  336. matrixDebugStateCounter--;
  337. // Output stats on number of scans being done per USB send
  338. print( NL );
  339. info_msg("Max scans: ");
  340. printHex( matrixMaxScans );
  341. print( NL );
  342. info_msg("Previous scans: ");
  343. printHex( matrixPrevScans );
  344. print( NL );
  345. // Output current scan number
  346. info_msg("Scan Number: ");
  347. printHex( scanNum );
  348. print( NL );
  349. // Display the state info for each key
  350. print("<key>:<previous state><current state> <active count> <inactive count>");
  351. for ( uint8_t key = 0; key < Matrix_maxKeys; key++ )
  352. {
  353. // Every 4 keys, put a newline
  354. if ( key % 4 == 0 )
  355. print( NL );
  356. print("\033[1m0x");
  357. printHex_op( key, 2 );
  358. print("\033[0m");
  359. print(":");
  360. Matrix_keyPositionDebug( Matrix_scanArray[ key ].prevState );
  361. Matrix_keyPositionDebug( Matrix_scanArray[ key ].curState );
  362. print(" 0x");
  363. printHex_op( Matrix_scanArray[ key ].activeCount, 4 );
  364. print(" 0x");
  365. printHex_op( Matrix_scanArray[ key ].inactiveCount, 4 );
  366. print(" ");
  367. }
  368. print( NL );
  369. }
  370. }
  371. // ----- CLI Command Functions -----
  372. void cliFunc_matrixDebug ( char* args )
  373. {
  374. // Parse number from argument
  375. // NOTE: Only first argument is used
  376. char* arg1Ptr;
  377. char* arg2Ptr;
  378. CLI_argumentIsolation( args, &arg1Ptr, &arg2Ptr );
  379. // Set the matrix debug flag depending on the argument
  380. // If no argument, set to scan code only
  381. // If set to T, set to state transition
  382. switch ( arg1Ptr[0] )
  383. {
  384. // T as argument
  385. case 'T':
  386. case 't':
  387. matrixDebugMode = matrixDebugMode != 2 ? 2 : 0;
  388. break;
  389. // No argument
  390. case '\0':
  391. matrixDebugMode = matrixDebugMode != 1 ? 1 : 0;
  392. break;
  393. // Invalid argument
  394. default:
  395. return;
  396. }
  397. print( NL );
  398. info_msg("Matrix Debug Mode: ");
  399. printInt8( matrixDebugMode );
  400. }
  401. void cliFunc_matrixState ( char* args )
  402. {
  403. // Parse number from argument
  404. // NOTE: Only first argument is used
  405. char* arg1Ptr;
  406. char* arg2Ptr;
  407. CLI_argumentIsolation( args, &arg1Ptr, &arg2Ptr );
  408. // Default to 1 if no argument is given
  409. matrixDebugStateCounter = 1;
  410. if ( arg1Ptr[0] != '\0' )
  411. {
  412. matrixDebugStateCounter = (uint16_t)numToInt( arg1Ptr );
  413. }
  414. }