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

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