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.

scan_loop.c 14KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573
  1. /* Copyright (C) 2011 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. // AVR Includes
  23. #include <avr/interrupt.h>
  24. #include <avr/io.h>
  25. #include <util/delay.h>
  26. // Project Includes
  27. #include <led.h>
  28. #include <print.h>
  29. // Local Includes
  30. #include "scan_loop.h"
  31. // ----- Defines -----
  32. // Pinout Defines
  33. #define CLOCK_PORT PORTB
  34. #define CLOCK_DDR DDRB
  35. #define CLOCK_PIN 0
  36. // ----- Macros -----
  37. // Make sure we haven't overflowed the buffer
  38. #define bufferAdd(byte) \
  39. if ( KeyIndex_BufferUsed < KEYBOARD_BUFFER ) \
  40. KeyIndex_Buffer[KeyIndex_BufferUsed++] = byte
  41. #define setLED(id, status) \
  42. status = status ? 0 : 1; \
  43. scan_setLED( id, status )
  44. // ----- Variables -----
  45. // Buffer used to inform the macro processing module which keys have been detected as pressed
  46. volatile uint8_t KeyIndex_Buffer[KEYBOARD_BUFFER];
  47. volatile uint8_t KeyIndex_BufferUsed;
  48. volatile uint8_t currentWaveState = 0;
  49. volatile uint8_t calcLED = 0;
  50. volatile uint8_t insertLED = 0;
  51. volatile uint8_t shiftLockLED = 0;
  52. volatile uint8_t schedLED = 0;
  53. volatile uint8_t drawLED = 0;
  54. // ----- Function Declarations -----
  55. void scan_diagnostics( void );
  56. void processKeyValue( uint8_t keyValue );
  57. void scan_diagnostics( void );
  58. void scan_setRepeatStart( uint8_t n );
  59. void scan_readSwitchStatus( void );
  60. void scan_repeatControl( uint8_t on );
  61. void scan_enableKeyboard( uint8_t enable );
  62. void scan_setRepeatRate( uint8_t n );
  63. void scan_setLED( uint8_t ledNumber, uint8_t on );
  64. void scan_readLED( void );
  65. // ----- Interrupt Functions -----
  66. // Generates a constant external clock
  67. ISR( TIMER1_COMPA_vect )
  68. {
  69. if ( currentWaveState )
  70. {
  71. CLOCK_PORT &= ~(1 << CLOCK_PIN);
  72. currentWaveState--;
  73. }
  74. else
  75. {
  76. CLOCK_PORT |= (1 << CLOCK_PIN);
  77. currentWaveState++;
  78. }
  79. }
  80. // USART Receive Buffer Full Interrupt
  81. ISR(USART1_RX_vect)
  82. {
  83. cli(); // Disable Interrupts
  84. uint8_t keyValue = 0x00;
  85. // Read the raw packet from the USART
  86. keyValue = UDR1;
  87. // Debug
  88. char tmpStr[6];
  89. hexToStr( keyValue, tmpStr );
  90. dPrintStrs( tmpStr, " " );
  91. // Process the scancode
  92. if ( keyValue != 0x00 )
  93. processKeyValue( keyValue );
  94. sei(); // Re-enable Interrupts
  95. }
  96. // ----- Functions -----
  97. // Setup
  98. inline void scan_setup()
  99. {
  100. // Setup Timer Pulse (16 bit)
  101. // 16 MHz / (2 * Prescaler * (1 + OCR1A)) = 1204.8 baud (820 us)
  102. // Prescaler is 1
  103. /*
  104. TCCR1B = 0x09;
  105. OCR1AH = 0x19;
  106. OCR1AL = 0xEF;
  107. TIMSK1 = (1 << OCIE1A);
  108. CLOCK_DDR = (1 << CLOCK_PIN);
  109. */
  110. // 16 MHz / (2 * Prescaler * (1 + OCR1A)) = 1200.1 baud
  111. // Prescaler is 1
  112. // Twice every 1200 baud (actually 1200.1, timer isn't accurate enough)
  113. // This is close to 820 us, but a bit slower
  114. cli();
  115. TCCR1B = 0x09;
  116. OCR1AH = 0x1A;
  117. OCR1AL = 0x09;
  118. TIMSK1 = (1 << OCIE1A);
  119. CLOCK_DDR = (1 << CLOCK_PIN);
  120. // Setup the the USART interface for keyboard data input
  121. // Setup baud rate
  122. // 16 MHz / ( 16 * Baud ) = UBRR
  123. // Baud <- 1200 as per the spec (see datasheet archives), rounding to 1200.1 (as that's as accurate as the timer can be)
  124. // Thus UBRR = 833.26 -> round to 833
  125. uint16_t baud = 833; // Max setting of 4095
  126. UBRR1H = (uint8_t)(baud >> 8);
  127. UBRR1L = (uint8_t)baud;
  128. // Enable the receiver, transitter, and RX Complete Interrupt
  129. UCSR1B = 0x98;
  130. // Set frame format: 8 data, no stop bits or parity
  131. // Synchrounous USART mode
  132. // Tx Data on Falling Edge, Rx on Rising
  133. UCSR1C = 0x47;
  134. sei();
  135. // Reset the keyboard before scanning, we might be in a wierd state
  136. _delay_ms( 50 );
  137. scan_resetKeyboard();
  138. _delay_ms( 5000 ); // Wait for the reset command to finish enough for new settings to take hold afterwards
  139. scan_setRepeatRate( 0x00 ); // Set the fastest repeat rate
  140. }
  141. // Main Detection Loop
  142. // Nothing is required here with the Epson QX-10 Keyboards as the interrupts take care of the inputs
  143. inline uint8_t scan_loop()
  144. {
  145. return 0;
  146. }
  147. // TODO
  148. void processKeyValue( uint8_t keyValue )
  149. {
  150. // Detect LED Status
  151. uint8_t inputType = keyValue & 0xC0;
  152. // Determine the input type
  153. switch ( inputType )
  154. {
  155. // LED Status
  156. case 0xC0:
  157. // Binary Representation: 1100 llln
  158. // Hex Range: 0xC0 to 0xCF
  159. // - First 3 bits determine which LED (0 to 7)
  160. // - Last bit is whether the LED is On (1) or Off (0)
  161. // 000 - N/A (A)
  162. // 001 - N/A (B)
  163. // 010 - INSERT
  164. // 011 - SHIFT LOCK
  165. // 100 - N/A (C)
  166. // 101 - DRAW
  167. // 110 - SCHED
  168. // 111 - CALC
  169. break;
  170. // SW (Switch) Status
  171. case 0x80:
  172. {
  173. // Binary Representation: 1000 dddn
  174. // Hex Range: 0x80 to 0x8F
  175. // - First 3 bits determine which DB (KRTN) (See datasheet)
  176. // - Last bit is whether the key is enabled
  177. // 000 - N/A?
  178. // 001 - N/A?
  179. // 010 - Right SHIFT
  180. // 011 - Left SHIFT
  181. // 100 - N/A?
  182. // 101 - Left CTRL
  183. // 110 - GRPH SHIFT
  184. // 111 - Right CTRL
  185. // Detect Modifier Press/Release
  186. uint8_t press = keyValue & 0x01;
  187. // Modifier Press Detected
  188. if ( press )
  189. {
  190. // Make sure the key isn't already in the buffer
  191. for ( uint8_t c = 0; c < KeyIndex_BufferUsed + 1; c++ )
  192. {
  193. // Key isn't in the buffer yet
  194. if ( c == KeyIndex_BufferUsed )
  195. {
  196. bufferAdd( keyValue );
  197. break;
  198. }
  199. // Key already in the buffer
  200. if ( KeyIndex_Buffer[c] == keyValue )
  201. break;
  202. }
  203. }
  204. // Modifier Release Detected
  205. else
  206. {
  207. uint8_t actualKeyValue = keyValue | 0x01;
  208. // Check for the released key, and shift the other keys lower on the buffer
  209. uint8_t c;
  210. for ( c = 0; c < KeyIndex_BufferUsed; c++ )
  211. {
  212. // Key to release found
  213. if ( KeyIndex_Buffer[c] == actualKeyValue )
  214. {
  215. // Shift keys from c position
  216. for ( uint8_t k = c; k < KeyIndex_BufferUsed - 1; k++ )
  217. KeyIndex_Buffer[k] = KeyIndex_Buffer[k + 1];
  218. // Decrement Buffer
  219. KeyIndex_BufferUsed--;
  220. break;
  221. }
  222. }
  223. // Error case (no key to release)
  224. if ( c == KeyIndex_BufferUsed + 1 )
  225. {
  226. errorLED( 1 );
  227. char tmpStr[6];
  228. hexToStr( keyValue, tmpStr );
  229. erro_dPrint( "Could not find key to release: ", tmpStr );
  230. }
  231. }
  232. break;
  233. }
  234. // Key code
  235. default:
  236. // Binary Representation: 0ddd pppp
  237. // Hex Range: 0x00 to 0x7F
  238. // - First 3 bits determine which DB (KRTN) (See datasheet)
  239. // - Last 4 bits corresond to the KSC signals (P13, P12, P11, P10 respectively)
  240. // Or, that can be read as, each key has it's own keycode (with NO release code)
  241. // Modifiers are treated differently
  242. // Add the key to the buffer, if it isn't already in the current Key Buffer
  243. for ( uint8_t c = 0; c < KeyIndex_BufferUsed + 1; c++ )
  244. {
  245. // Key isn't in the buffer yet
  246. if ( c == KeyIndex_BufferUsed )
  247. {
  248. bufferAdd( keyValue );
  249. break;
  250. }
  251. // Key already in the buffer
  252. if ( KeyIndex_Buffer[c] == keyValue )
  253. break;
  254. }
  255. // Special Internal Key Mapping/Functions
  256. switch ( keyValue )
  257. {
  258. // LED Test
  259. case 0x0A: // CALC
  260. setLED( 0x07, calcLED ); // 0x4F
  261. break;
  262. case 0x0B: // SCHED
  263. setLED( 0x0E, schedLED ); // 0x5D
  264. break;
  265. case 0x0C: // DRAW
  266. setLED( 0x0D, drawLED ); // 0x5B
  267. break;
  268. case 0x42: // SHIFT LOCK
  269. setLED( 0x0B, shiftLockLED ); // 0x57
  270. break;
  271. case 0x5E: // INSERT
  272. setLED( 0x02, insertLED ); // 0x45
  273. break;
  274. /*
  275. // TEST
  276. case 0x51:
  277. scan_resetKeyboard();
  278. break;
  279. case 0x52:
  280. scan_diagnostics();
  281. break;
  282. case 0x53:
  283. scan_setRepeatStart( 0x00 );
  284. break;
  285. case 0x54:
  286. scan_readSwitchStatus();
  287. break;
  288. case 0x55:
  289. scan_repeatControl( 0x00 );
  290. break;
  291. case 0x56:
  292. scan_repeatControl( 0x01 );
  293. break;
  294. case 0x57:
  295. scan_enableKeyboard( 0x00 );
  296. break;
  297. case 0x58:
  298. scan_enableKeyboard( 0x01 );
  299. break;
  300. case 0x59:
  301. scan_setRepeatRate( 0x00 );
  302. break;
  303. case 0x5A:
  304. scan_readLED();
  305. break;
  306. */
  307. }
  308. break;
  309. }
  310. }
  311. // Send data
  312. // See below functions for the input sequences for the Epson QX-10 Keyboard
  313. uint8_t scan_sendData( uint8_t dataPayload )
  314. {
  315. // Debug
  316. char tmpStr[6];
  317. hexToStr( dataPayload, tmpStr );
  318. info_dPrint( tmpStr, " " );
  319. UDR1 = dataPayload;
  320. return 0;
  321. }
  322. // Signal KeyIndex_Buffer that it has been properly read
  323. inline void scan_finishedWithBuffer( void )
  324. {
  325. return;
  326. }
  327. // Signal that the keys have been properly sent over USB
  328. // For the Epson QX-10 only the modifier keys have release signals
  329. // Therefore, only 5 keys could possibly be assigned as a modifiers
  330. // The rest of the keys are single press (like the Kaypro keyboards)
  331. //
  332. // However, this differentiation causes complications on how the key signals are discarded and used
  333. // The single keypresses must be discarded immediately, while the modifiers must be kept
  334. inline void scan_finishedWithUSBBuffer( void )
  335. {
  336. uint8_t foundModifiers = 0;
  337. // Look for all of the modifiers present, there is a max of 8 (but only keys for 5 on the HASCI version)
  338. for ( uint8_t c = 0; c < KeyIndex_BufferUsed; c++ )
  339. {
  340. // The modifier range is from 0x80 to 0x8F (well, the last bit is the ON/OFF signal, but whatever...)
  341. if ( KeyIndex_Buffer[c] <= 0x8F && KeyIndex_Buffer[c] >= 0x80 )
  342. {
  343. // Add the modifier back into the the Key Buffer
  344. KeyIndex_Buffer[foundModifiers] = KeyIndex_Buffer[c];
  345. foundModifiers++;
  346. }
  347. }
  348. // Adjust the size of the new Key Buffer
  349. KeyIndex_BufferUsed = foundModifiers;
  350. /* Non-working, too slow (too much traffic on the bus)
  351. // Poll the modifiers using an input command
  352. uint8_t oldBuffer = KeyIndex_BufferUsed;
  353. KeyIndex_BufferUsed = 0;
  354. if ( oldBuffer )
  355. scan_readSwitchStatus();
  356. */
  357. }
  358. // Reset/Hold keyboard
  359. // Warning! This will cause the keyboard to not send any data, so you can't disable with a keypress
  360. // The Epson QX-10 Keyboards have a command used to lock the keyboard output
  361. void scan_lockKeyboard( void )
  362. {
  363. scan_enableKeyboard( 0x00 );
  364. }
  365. void scan_unlockKeyboard( void )
  366. {
  367. scan_enableKeyboard( 0x01 );
  368. }
  369. // Reset Keyboard
  370. // Does the following
  371. // - Clears the keycode buffer (32 characters)
  372. // - Validates repeat function (what does this do?)
  373. // - Sets repeat start time (500 ms)
  374. // - Sets repeat interval (50 ms)
  375. // - Turns off all LEDs
  376. void scan_resetKeyboard( void )
  377. {
  378. // Reset command for the QX-10 Keyboard
  379. scan_sendData( 0xE0 );
  380. // Empty buffer, now that keyboard has been reset
  381. KeyIndex_BufferUsed = 0;
  382. }
  383. // TODO Check
  384. // Runs Diagnostics on the keyboard
  385. // - First does a reset (see scan_resetKeyboard)
  386. // - Blinks all of the LEDs one after another
  387. // - Outputs 0x00 if no keys are pressed
  388. // - Outputs 0xFF if any keys are being pressed
  389. void scan_diagnostics( void )
  390. {
  391. // Send reset command with diagnositics
  392. scan_sendData( 0xE7 );
  393. }
  394. // TODO Check
  395. // Set Repeat Interval Start
  396. // 300 ms + n * 25 ms
  397. // Interval after which to start the repeated keys
  398. void scan_setRepeatStart( uint8_t n )
  399. {
  400. // Send command
  401. // Binary Representation: 000n nnnn
  402. // Hex boundaries 0x00 to 0x1F
  403. // 300 ms to 1075 ms (intervals of 25 ms)
  404. scan_sendData( n );
  405. }
  406. // Read Switch Status (preferential to actual keypress outputs)
  407. // 000 - N/A?
  408. // 001 - N/A?
  409. // 010 - Right SHIFT
  410. // 011 - Left SHIFT
  411. // 100 - N/A?
  412. // 101 - Left CTRL
  413. // 110 - GRPH SHIFT
  414. // 111 - Right CTRL
  415. void scan_readSwitchStatus( void )
  416. {
  417. scan_sendData( 0x80 );
  418. }
  419. // TODO Check
  420. // Repeat Control
  421. // 0x00 Stops repeat function
  422. // 0x01 Enables repeat function
  423. void scan_repeatControl( uint8_t on )
  424. {
  425. // Send command
  426. // Binary Representation: 101X XXXn
  427. // Hex options: 0xA0 or 0xA1
  428. scan_sendData( 0xA0 | on );
  429. }
  430. // TODO Check
  431. // Enable Sending Keyboard Data
  432. // 0x00 Stops keycode transmission
  433. // 0x01 Enables keycode transmission
  434. void scan_enableKeyboard( uint8_t enable )
  435. {
  436. // Send command
  437. // Binary Representation: 110X XXXn
  438. // Hex options: 0xC0 or 0xC1
  439. scan_sendData( 0xC0 | enable );
  440. }
  441. // Set Repeat Interval
  442. // 30 ms + n * 5 ms
  443. // Period between sending each repeated key after the initial interval
  444. void scan_setRepeatRate( uint8_t n )
  445. {
  446. // Send command
  447. // Binary Representation: 001n nnnn
  448. // Hex options: 0x00 to 0x1F
  449. // 30 ms to 185 ms (intervals of 5 ms)
  450. scan_sendData( 0x20 | n );
  451. }
  452. // Turn On/Off LED
  453. // 0x00 LED Off
  454. // 0x01 LED On
  455. //
  456. // 8 LEDs max (Note: 5 connected on my board, there is 1 position empty on the PCB for a total of 6)
  457. // 0 to 7 (0x0 to 0x7)
  458. void scan_setLED( uint8_t ledNumber, uint8_t on )
  459. {
  460. // Send command
  461. // Binary Representation: 010l llln
  462. // Hex options: 0x40 to 0x4F
  463. // The spec is NOT accurate (especially about the "don't care" bit)
  464. // llll n - Usage
  465. // 0000 X - N/A (1)
  466. // 0001 X - N/A (2)
  467. // 0010 1 - INSERT On
  468. // 0011 0 - SHIFT LOCK Off
  469. // 0100 X - N/A (3)
  470. // 0101 0 - DRAW Off
  471. // 0110 0 - SCHED Off
  472. // 0111 1 - CALC On
  473. // 1000 X - N/A (1)
  474. // 1001 X - N/A (2)
  475. // 1010 0 - INSERT Off
  476. // 1011 1 - SHIFT LOCK On
  477. // 1100 X - N/A (3)
  478. // 1101 1 - DRAW On
  479. // 1110 1 - SCHED On
  480. // 1111 0 - CALC Off
  481. uint8_t off = 0;
  482. if ( !on )
  483. {
  484. off = 0x10;
  485. }
  486. scan_sendData( ( 0x40 | (ledNumber << 1) | on ) ^ off );
  487. }
  488. // Read LED Status
  489. // High priority data output (may overwrite some keycode data)
  490. void scan_readLED( void )
  491. {
  492. scan_sendData( 0x7F );
  493. }