1 /* Copyright (C) 2012 by Jacob Alexander
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:
10 * The above copyright notice and this permission notice shall be included in
11 * all copies or substantial portions of the Software.
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
22 // ----- Includes -----
25 #include <avr/interrupt.h>
27 #include <util/delay.h>
34 #include "scan_loop.h"
38 // ----- Defines -----
41 #define REQUEST_PORT PORTD
42 #define REQUEST_DDR DDRD
44 #define DATA_READ PIND
45 #define DATA_PORT PORTD
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
56 #define READ_DATA DATA_READ & (1 << DATA_PIN) ? 0 : 1
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
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
68 // ----- Variables -----
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;
76 // ----- Function Declarations -----
78 void processPacketValue( uint16_t packetValue );
82 // ----- Interrupt Functions -----
84 // XXX - None Required
88 // ----- Functions -----
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()
98 DATA_DDR &= ~(1 << DATA_PIN); // Set to input
99 DATA_PORT |= (1 << DATA_PIN); // Set to pull-up resistor
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
105 // Reset the keyboard before scanning, we might be in a wierd state
107 scan_resetKeyboard();
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.
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
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()
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
139 // Now that the scan loop has been entered, we don't have to worry about interrupts stealing
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
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!).
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
165 // _delay_us is available to use, fortunately.
167 // Input Packet Storage (before being processed)
168 uint16_t incomingPacket[PACKET_STORAGE];
169 uint8_t numberOfIncomingPackets = 0;
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
175 uint16_t failures = 0;
177 // Continue waiting for a start bit until MAX_FAILURES has been reached (~5ms of nothing)
178 while ( failures <= MAX_FAILURES )
180 // Attempt to find the start bit
181 while ( samples < MAX_SAMPLES )
186 // If data is valid, increment
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 )
207 // If 10 valid samples of the start bit were obtained,
208 if ( samples >= MAX_SAMPLES )
210 // Clean out the old packet memory
211 incomingPacket[numberOfIncomingPackets] = 0;
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++ )
216 // Wait until the middle of the next bit
219 // Append the current bit value
220 incomingPacket[numberOfIncomingPackets] |= (READ_DATA << c);
223 // Packet finished, increment counter
224 numberOfIncomingPackets++;
228 // Stop the keyboard input
231 // Finished receiving data from keyboard, start packet processing
232 for ( uint8_t packet = 0; packet < numberOfIncomingPackets; packet++ )
233 processPacketValue( incomingPacket[packet] );
238 // Read in the Packet Data, and decide what to do with it
239 void processPacketValue( uint16_t packetValue )
243 // A is the first bit received (bit 0), T is the last
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
250 // B -> H - Modifier enabled bits
251 // - Each bit represents a different modifier "mode"
259 // I -> L - ?? No idea yet...
260 // - The bits change for some combinations, but not pattern has been found yet...
265 // M -> T - Scan Code
266 // - Bits are organized from low to high (8 bit value)
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;
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 );
293 // - Key Release mechanism
295 // Compute Modifier keys
298 // Deal with special scan codes
302 //bufferAdd( scanCode ); TODO - Uncomment when ready for USB output
308 // NOTE: Does nothing with the Univac-Sperry F3W9
309 uint8_t scan_sendData( uint8_t dataPayload )
314 // Signal KeyIndex_Buffer that it has been properly read
315 inline void scan_finishedWithBuffer( void )
320 // Signal that the keys have been properly sent over USB
322 inline void scan_finishedWithUSBBuffer( void )
325 uint8_t foundModifiers = 0;
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++ )
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 )
333 // Add the modifier back into the the Key Buffer
334 KeyIndex_Buffer[foundModifiers] = KeyIndex_Buffer[c];
339 // Adjust the size of the new Key Buffer
340 KeyIndex_BufferUsed = foundModifiers;
344 // Reset/Hold keyboard
345 // NOTE: Does nothing with the Univac-Sperry F3W9
346 void scan_lockKeyboard( void )
350 // NOTE: Does nothing with the Univac-Sperry F3W9
351 void scan_unlockKeyboard( void )
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 )
361 // Initiate data request line, but don't read the incoming data
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.