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

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