Kiibohd Controller
Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.
Repozitorijs ir arhivēts. Tam var aplūkot failus un to var klonēt, bet nevar iesūtīt jaunas izmaiņas, kā arī atvērt jaunas problēmas/izmaiņu pieprasījumus.

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