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