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