1 /* Copyright (C) 2012,2014 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 <Lib/ScanLib.h>
32 #include "scan_loop.h"
36 // ----- Defines -----
39 #define REQUEST_PORT PORTD
40 #define REQUEST_DDR DDRD
42 #define DATA_READ PIND
43 #define DATA_PORT PORTD
47 #define MAX_SAMPLES 10
48 #define MAX_FAILURES 3731
49 #define PACKET_STORAGE 24 // At worst only 8 packets, but with you keypresses you can get more
54 #define READ_DATA DATA_READ & (1 << DATA_PIN) ? 0 : 1
56 #define REQUEST_DATA() REQUEST_DDR &= ~(1 << REQUEST_PIN) // Start incoming keyboard transfer
57 #define STOP_DATA() REQUEST_DDR |= (1 << REQUEST_PIN) // Stop incoming keyboard data
61 // ----- Variables -----
63 // Buffer used to inform the macro processing module which keys have been detected as pressed
64 volatile uint8_t KeyIndex_Buffer[KEYBOARD_BUFFER];
65 volatile uint8_t KeyIndex_BufferUsed;
69 // ----- Function Declarations -----
71 void processPacketValue( uint16_t packetValue );
75 // ----- Interrupt Functions -----
77 // XXX - None Required
81 // ----- Functions -----
84 // This setup is very simple, as there is no extra hardware used in this scan module, other than GPIOs.
85 // To be nice, we wait a little bit after powering on, and dump any of the pending keyboard data.
86 // Afterwards (as long as no keys were being held), the keyboard should have a clean buffer, and be ready to go.
87 // (Even if keys were held down, everything should probably still work...)
88 inline void Scan_setup()
91 DATA_DDR &= ~(1 << DATA_PIN); // Set to input
92 DATA_PORT |= (1 << DATA_PIN); // Set to pull-up resistor
94 // Setup the REQUEST pin
95 REQUEST_PORT |= (1 << REQUEST_PIN); // Set to output
96 STOP_DATA(); // Set the line high to stop incoming data
103 info_print("Pins Setup");
105 // Reset the keyboard before scanning, we might be in a wierd state
107 //Scan_resetKeyboard();
110 info_print("Keyboard Buffer Flushed");
114 // Main Detection Loop
115 // The Univac-Sperry F3W9 has a convenient feature, an internal 8 key buffer
116 // This buffer is only emptied (i.e. sent over the bus) when the REQUEST line is held high
117 // Because of this, we can utilize the Scan_loop to do all of the critical processing,
118 // without having to resort to interrupts, giving the data reading 100% of the CPU.
119 // This is because the USB interrupts can wait until the Scan_loop is finished to continue.
121 // Normally, this approach isn't taken, as it's easier/faster/safer to use Teensy hardware shift registers
122 // for serial data transfers.
123 // However, since the Univac-Sperry F3W9 sends 20 bit packets (including the start bit), the Teensy
124 // doesn't have a shift register large enough (9 bit max), to hold the data.
125 // So the line must be polled manually using CPU cycles
127 // Another interesting feature is that there are 2 data lines.
128 // Output and /Output (NOT'ted version).
129 // Not really useful here, but could be used for error checking, or eliminating an external NOT gate if
130 // we were using (but can't...) a hardware decoder like a USART.
131 inline uint8_t Scan_loop()
135 // - Packets are 20 bits long, including the start bit
136 // - Each bit is ~105 usecs in length
137 // - Thus the average packet length is 2.205 msecs
138 // - Each packet is separated by at least 240 usecs (during a buffer unload)
139 // - While holding the key down, each packet has a space of about 910 usecs
140 // - 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)
141 // - There is no timing danger for holding the request line, just that data may come in when you don't want it
143 // Now that the scan loop has been entered, we don't have to worry about interrupts stealing
149 // For these calculations to work out properly, then Teensy should be running at 16 MHz
150 // - 1 bit : 105 usecs is 16 000 000 * 0.000105 = 1680 instructions
151 // - Bit centering : 52.5 usecs is 16 000 000 * 0.0000525 = 840 instructions
152 // - Delay : 5 msecs is 16 000 000 * 0.005 = 80 000 instructions
153 // - Microsecond : 1 usec is 16 000 000 * 0.000001 = 16 instructions
155 // Now, either I can follow these exactly, or based upon the fact that I have >840 tries to find the
156 // the start bit, and >1680 tries to read the subsequent bits, I have some "flex" time.
157 // Knowing this, I can make some assumptions that because I'm only reading a total of 20 bits, and will
158 // be re-centering for each packet.
159 // This will allow for less worrying about compiler optimizations (and porting!).
161 // The basic idea is to find a "reliable" value for the start bit, e.g. read it ~10 times.
162 // Using a for-loop and some addition counters, this should eat up approximately 20-30 instructions per read
163 // (very loose estimation).
164 // So reading 10 * 30 instructions = 300 instructions, which is much less than 840 instructions to where the
165 // bit center is, but is close enough that further delays of ~>1680 instructions will put the next read
166 // within the next bit period.
167 // This is all possible because interrupts are disabled at this point, otherwise, all of this reasoning
169 // _delay_us is available to use, fortunately.
171 // Input Packet Storage (before being processed)
172 uint16_t incomingPacket[PACKET_STORAGE];
173 uint8_t numberOfIncomingPackets = 0;
175 // Sample the data line for ~5 ms, looking for a start bit
176 // - Sampling every 1 usecs, looking for 10 good samples
177 // - Accumulated samples will dumped if a high is detected
179 uint16_t failures = 0;
181 // Continue waiting for a start bit until MAX_FAILURES has been reached (~5ms of nothing)
182 while ( failures <= MAX_FAILURES )
184 // Attempt to find the start bit
185 while ( samples < MAX_SAMPLES )
190 // If data is valid, increment
201 // After ~5ms of failures, break the loop
202 // Each failure is approx 5 instructions + 1 usec, or approximately 1.34 usec)
203 // So ~3731 failures for ~5ms
204 // Being exact doesn't matter, as this is just to let the other parts of the
205 // controller do some processing
206 if ( failures > MAX_FAILURES )
211 // If 10 valid samples of the start bit were obtained,
212 if ( samples >= MAX_SAMPLES )
214 // Clean out the old packet memory
215 incomingPacket[numberOfIncomingPackets] = 0;
217 // Read the next 19 bits into memory (bit 0 is the start bit, which is always 0)
218 for ( uint8_t c = 1; c < 20; c++ )
220 // Wait until the middle of the next bit
223 // Append the current bit value
224 incomingPacket[numberOfIncomingPackets] |= (READ_DATA << c);
227 // Packet finished, increment counter
228 numberOfIncomingPackets++;
232 // Stop the keyboard input
235 // Finished receiving data from keyboard, start packet processing
236 for ( uint8_t packet = 0; packet < numberOfIncomingPackets; packet++ )
237 processPacketValue( incomingPacket[packet] );
242 // Read in the Packet Data, and decide what to do with it
243 void processPacketValue( uint16_t packetValue )
247 // A is the first bit received (bit 0), T is the last
249 // | Modifier? | ?? | Scan Code |
250 // A B C D E F G H I J K L M N O P Q R S T
254 // B -> H - Modifier enabled bits
255 // - Each bit represents a different modifier "mode"
263 // I -> L - ?? No idea yet...
264 // - The bits change for some combinations, but not pattern has been found yet...
269 // M -> T - Scan Code
270 // - Bits are organized from low to high (8 bit value)
280 // Separate packet into sections
281 uint8_t scanCode = (packetValue & 0xFF000) << 12;
282 uint8_t modifiers = (packetValue & 0x000FE);
283 uint8_t extra = (packetValue & 0x00F00) << 8;
289 hexToStr_op( scanCode, tmpStr1, 2 );
290 hexToStr_op( modifiers, tmpStr2, 2 );
291 hexToStr_op( extra, tmpStr3, 2 );
292 dbug_dPrint( "Scancode: 0x", tmpStr1, " Modifiers: 0x", tmpStr2, " Extra: 0x", tmpStr3 );
293 dbug_dPrint( "Packet: 0x", tmpStr2, tmpStr3, tmpStr1 );
297 // - Key Release mechanism
299 // Compute Modifier keys
302 // Deal with special scan codes
306 //Macro_bufferAdd( scanCode ); TODO - Uncomment when ready for USB output
312 // NOTE: Does nothing with the Univac-Sperry F3W9
313 uint8_t Scan_sendData( uint8_t dataPayload )
318 // Signal KeyIndex_Buffer that it has been properly read
319 inline void Scan_finishedWithBuffer( uint8_t sentKeys )
324 // Signal that the keys have been properly sent over USB
326 inline void Scan_finishedWithUSBBuffer( uint8_t sentKeys )
329 uint8_t foundModifiers = 0;
331 // Look for all of the modifiers present, there is a max of 8 (but only keys for 5 on the HASCI version)
332 for ( uint8_t c = 0; c < KeyIndex_BufferUsed; c++ )
334 // The modifier range is from 0x80 to 0x8F (well, the last bit is the ON/OFF signal, but whatever...)
335 if ( KeyIndex_Buffer[c] <= 0x8F && KeyIndex_Buffer[c] >= 0x80 )
337 // Add the modifier back into the the Key Buffer
338 KeyIndex_Buffer[foundModifiers] = KeyIndex_Buffer[c];
343 // Adjust the size of the new Key Buffer
344 KeyIndex_BufferUsed = foundModifiers;
348 // Reset/Hold keyboard
349 // NOTE: Does nothing with the Univac-Sperry F3W9
350 void Scan_lockKeyboard( void )
354 // NOTE: Does nothing with the Univac-Sperry F3W9
355 void Scan_unlockKeyboard( void )
360 // - Holds the input read line high to flush the buffer
361 // - This does not actually reset the keyboard, but always seems brings it to a sane state
362 // - Won't work fully if keys are being pressed done at the same time
363 void Scan_resetKeyboard( void )
365 // Initiate data request line, but don't read the incoming data
368 // We shouldn't be receiving more than 8 packets (and maybe +1 error signal)
369 // This is around 22 ms of data, so a delay of 50 ms should be sufficient.