]> git.donarmstrong.com Git - kiibohd-controller.git/blob - Scan/UnivacF3W9/scan_loop.c
Adding inital outline for Univac-Sperry F3W9 keyboard.
[kiibohd-controller.git] / Scan / UnivacF3W9 / scan_loop.c
1 /* Copyright (C) 2012 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 REQUEST_PORT PORTD
42 #define REQUEST_DDR  DDRD
43 #define REQUEST_PIN  3
44 #define DATA_READ    PIND
45 #define DATA_PORT    PORTD
46 #define DATA_DDR     DDRD
47 #define DATA_PIN     2
48
49 #define MAX_SAMPLES    10
50 #define MAX_FAILURES   3731
51 #define PACKET_STORAGE 24   // At worst only 8 packets, but with you keypresses you can get more
52
53
54 // ----- Macros -----
55
56 #define READ_DATA         DATA_READ &   (1 << DATA_PIN) ? 0 : 1
57
58 #define REQUEST_DATA()  REQUEST_DDR &= ~(1 << REQUEST_PIN) // Start incoming keyboard transfer
59 #define    STOP_DATA()  REQUEST_DDR |=  (1 << REQUEST_PIN) // Stop incoming keyboard data
60
61 // Make sure we haven't overflowed the buffer
62 #define bufferAdd(byte) \
63                 if ( KeyIndex_BufferUsed < KEYBOARD_BUFFER ) \
64                         KeyIndex_Buffer[KeyIndex_BufferUsed++] = byte
65
66
67
68 // ----- Variables -----
69
70 // Buffer used to inform the macro processing module which keys have been detected as pressed
71 volatile uint8_t KeyIndex_Buffer[KEYBOARD_BUFFER];
72 volatile uint8_t KeyIndex_BufferUsed;
73
74
75
76 // ----- Function Declarations -----
77
78 void processPacketValue( uint16_t packetValue );
79
80
81
82 // ----- Interrupt Functions -----
83
84 // XXX - None Required
85
86
87
88 // ----- Functions -----
89
90 // Setup
91 // This setup is very simple, as there is no extra hardware used in this scan module, other than GPIOs.
92 // To be nice, we wait a little bit after powering on, and dump any of the pending keyboard data.
93 // Afterwards (as long as no keys were being held), the keyboard should have a clean buffer, and be ready to go.
94 // (Even if keys were held down, everything should probably still work...)
95 inline void scan_setup()
96 {
97         // Setup the DATA pin
98         DATA_DDR  &= ~(1 << DATA_PIN); // Set to input
99         DATA_PORT |=  (1 << DATA_PIN); // Set to pull-up resistor
100
101         // Setup the REQUEST pin
102         REQUEST_DDR |= (1 << REQUEST_PIN); // Set to output
103         STOP_DATA(); // Set the line high to stop incoming data
104
105         // Reset the keyboard before scanning, we might be in a wierd state
106         _delay_ms( 50 );
107         scan_resetKeyboard();
108 }
109
110
111 // Main Detection Loop
112 // The Univac-Sperry F3W9 has a convenient feature, an internal 8 key buffer
113 // This buffer is only emptied (i.e. sent over the bus) when the REQUEST line is held high
114 // Because of this, we can utilize the scan_loop to do all of the critical processing,
115 //  without having to resort to interrupts, giving the data reading 100% of the CPU.
116 // This is because the USB interrupts can wait until the scan_loop is finished to continue.
117 //
118 // Normally, this approach isn't taken, as it's easier/faster/safer to use Teensy hardware shift registers
119 //  for serial data transfers.
120 // However, since the Univac-Sperry F3W9 sends 20 bit packets (including the start bit), the Teensy
121 //  doesn't have a shift register large enough (9 bit max), to hold the data.
122 // So the line must be polled manually using CPU cycles
123 //
124 // Another interesting feature is that there are 2 data lines.
125 // Output and /Output (NOT'ted version).
126 // Not really useful here, but could be used for error checking, or eliminating an external NOT gate if
127 //  we were using (but can't...) a hardware decoder like a USART.
128 inline uint8_t scan_loop()
129 {
130         // Protocol Notes:
131         // - Packets are 20 bits long, including the start bit
132         // - Each bit is ~105 usecs in length
133         // - Thus the average packet length is 2.205 msecs
134         // - Each packet is separated by at least 240 usecs (during a buffer unload)
135         // - While holding the key down, each packet has a space of about 910 usecs
136         // - A max of 8 keys can be sent at once (note, the arrow keys seem use 2 packets each, and thus take up twice as much buffer)
137         // - There is no timing danger for holding the request line, just that data may come in when you don't want it
138
139         // Now that the scan loop has been entered, we don't have to worry about interrupts stealing
140         //  precious cycles.
141         REQUEST_DATA();
142
143         // = Delays =
144         //
145         // For these calculations to work out properly, then Teensy should be running at 16 MHz
146         // - 1 bit         : 105   usecs is 16 000 000 * 0.000105  =   1680 instructions
147         // - Bit centering :  52.5 usecs is 16 000 000 * 0.0000525 =    840 instructions
148         // - Delay         :   5   msecs is 16 000 000 * 0.005     = 80 000 instructions
149         // - Microsecond   :   1   usec  is 16 000 000 * 0.000001  =     16 instructions
150         //
151         // Now, either I can follow these exactly, or based upon the fact that I have >840 tries to find the
152         //  the start bit, and >1680 tries to read the subsequent bits, I have some "flex" time.
153         // Knowing this, I can make some assumptions that because I'm only reading a total of 20 bits, and will
154         //  be re-centering for each packet.
155         // This will allow for less worrying about compiler optimizations (and porting!).
156
157         // The basic idea is to find a "reliable" value for the start bit, e.g. read it ~10 times.
158         // Using a for-loop and some addition counters, this should eat up approximately 20-30 instructions per read
159         //  (very loose estimation).
160         // So reading 10 * 30 instructions = 300 instructions, which is much less than 840 instructions to where the
161         //  bit center is, but is close enough that further delays of ~>1680 instructions will put the next read
162         //  within the next bit period.
163         // This is all possible because interrupts are disabled at this point, otherwise, all of this reasoning
164         //  would fall apart.
165         // _delay_us is available to use, fortunately.
166
167         // Input Packet Storage (before being processed)
168         uint16_t incomingPacket[PACKET_STORAGE];
169         uint8_t  numberOfIncomingPackets = 0;
170
171         // Sample the data line for ~5 ms, looking for a start bit
172         //  - Sampling every 1 usecs, looking for 10 good samples
173         //  - Accumulated samples will dumped if a high is detected
174         uint8_t  samples  = 0;
175         uint16_t failures = 0;
176
177         // Continue waiting for a start bit until MAX_FAILURES has been reached (~5ms of nothing)
178         while ( failures <= MAX_FAILURES )
179         {
180                 // Attempt to find the start bit
181                 while ( samples < MAX_SAMPLES )
182                 {
183                         // Delay first
184                         _delay_us( 1 );
185
186                         // If data is valid, increment
187                         if ( READ_DATA )
188                         {
189                                 samples++;
190                         }
191                         // Reset
192                         else
193                         {
194                                 samples = 0;
195                                 failures++;
196
197                                 // After ~5ms of failures, break the loop
198                                 // Each failure is approx 5 instructions + 1 usec, or approximately 1.34 usec)
199                                 // So ~3731 failures for ~5ms
200                                 // Being exact doesn't matter, as this is just to let the other parts of the
201                                 //  controller do some processing
202                                 if ( failures > MAX_FAILURES )
203                                         break;
204                         }
205                 }
206
207                 // If 10 valid samples of the start bit were obtained, 
208                 if ( samples >= MAX_SAMPLES )
209                 {
210                         // Clean out the old packet memory
211                         incomingPacket[numberOfIncomingPackets] = 0;
212
213                         // Read the next 19 bits into memory (bit 0 is the start bit, which is always 0)
214                         for ( uint8_t c = 1; c < 20; c++ )
215                         {
216                                 // Wait until the middle of the next bit
217                                 _delay_us( 105 );
218
219                                 // Append the current bit value
220                                 incomingPacket[numberOfIncomingPackets] |= (READ_DATA << c);
221                         }
222
223                         // Packet finished, increment counter
224                         numberOfIncomingPackets++;
225                 }
226         }
227
228         // Stop the keyboard input
229         STOP_DATA();
230
231         // Finished receiving data from keyboard, start packet processing
232         for ( uint8_t packet = 0; packet < numberOfIncomingPackets; packet++ )
233                 processPacketValue( incomingPacket[packet] );
234
235         return 0;
236 }
237
238 // Read in the Packet Data, and decide what to do with it
239 void processPacketValue( uint16_t packetValue )
240 {
241         // = Packet Layout =
242         //
243         // A is the first bit received (bit 0), T is the last
244         //
245         //   |  Modifier?  |  ??   |   Scan Code   |
246         //  A B C D E F G H I J K L M N O P Q R S T
247         //
248         // A      - Start bit
249         //          - Always Low
250         // B -> H - Modifier enabled bits
251         //          - Each bit represents a different modifier "mode"
252         //          - B -> Shift/Lock
253         //          - C -> ??
254         //          - D -> Func
255         //          - E -> ??
256         //          - F -> ??
257         //          - G -> ??
258         //          - H -> ??
259         // I -> L - ?? No idea yet...
260         //          - The bits change for some combinations, but not pattern has been found yet...
261         //          - I -> ??
262         //          - J -> ??
263         //          - K -> ??
264         //          - L -> ??
265         // M -> T - Scan Code
266         //          - Bits are organized from low to high (8 bit value)
267         //          - M -> Bit 1
268         //          - N -> Bit 2
269         //          - O -> Bit 3
270         //          - P -> Bit 4
271         //          - Q -> Bit 5
272         //          - R -> Bit 6
273         //          - S -> Bit 7
274         //          - T -> Bit 8
275
276         // Separate packet into sections
277         uint8_t scanCode  = (packetValue & 0xFF000) << 12;
278         uint8_t modifiers = (packetValue & 0x000FE);
279         uint8_t extra     = (packetValue & 0x00F00) << 8;
280
281         // Debug Info
282         char tmpStr1[3];
283         char tmpStr2[3];
284         char tmpStr3[3];
285         hexToStr_op( scanCode, tmpStr1, 2 );
286         hexToStr_op( modifiers, tmpStr2, 2 );
287         hexToStr_op( extra, tmpStr3, 2 );
288         dbug_dPrint( "Scancode: 0x", tmpStr1, " Modifiers: 0x", tmpStr2, " Extra: 0x", tmpStr3 );
289         dbug_dPrint( "Packet: 0x", tmpStr2, tmpStr3, tmpStr1 );
290
291         // TODO List
292         // - Modifier keys
293         // - Key Release mechanism
294
295         // Compute Modifier keys
296         // TODO
297
298         // Deal with special scan codes
299         switch ( scanCode )
300         {
301         default:
302                 //bufferAdd( scanCode ); TODO - Uncomment when ready for USB output
303                 break;
304         }
305 }
306
307 // Send data
308 // NOTE: Does nothing with the Univac-Sperry F3W9
309 uint8_t scan_sendData( uint8_t dataPayload )
310 {
311         return 0;
312 }
313
314 // Signal KeyIndex_Buffer that it has been properly read
315 inline void scan_finishedWithBuffer( void )
316 {
317         return;
318 }
319
320 // Signal that the keys have been properly sent over USB
321 // TODO
322 inline void scan_finishedWithUSBBuffer( void )
323 {
324         /*
325         uint8_t foundModifiers = 0;
326
327         // Look for all of the modifiers present, there is a max of 8 (but only keys for 5 on the HASCI version)
328         for ( uint8_t c = 0; c < KeyIndex_BufferUsed; c++ )
329         {
330                 // The modifier range is from 0x80 to 0x8F (well, the last bit is the ON/OFF signal, but whatever...)
331                 if ( KeyIndex_Buffer[c] <= 0x8F && KeyIndex_Buffer[c] >= 0x80 )
332                 {
333                         // Add the modifier back into the the Key Buffer
334                         KeyIndex_Buffer[foundModifiers] = KeyIndex_Buffer[c];
335                         foundModifiers++;
336                 }
337         }
338
339         // Adjust the size of the new Key Buffer
340         KeyIndex_BufferUsed = foundModifiers;
341         */
342 }
343
344 // Reset/Hold keyboard
345 // NOTE: Does nothing with the Univac-Sperry F3W9
346 void scan_lockKeyboard( void )
347 {
348 }
349
350 // NOTE: Does nothing with the Univac-Sperry F3W9
351 void scan_unlockKeyboard( void )
352 {
353 }
354
355 // Reset Keyboard
356 // - Holds the input read line high to flush the buffer
357 // - This does not actually reset the keyboard, but always seems brings it to a sane state
358 // - Won't work fully if keys are being pressed done at the same time
359 void scan_resetKeyboard( void )
360 {
361         // Initiate data request line, but don't read the incoming data
362         REQUEST_DATA();
363
364         // We shouldn't be receiving more than 8 packets (and maybe +1 error signal)
365         // This is around 22 ms of data, so a delay of 50 ms should be sufficient.
366         _delay_ms( 50 );
367
368         // Stop request line
369         STOP_DATA();
370 }
371