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 DATA_PORT PORTC
46 #define CLOCK_PORT PORTC
47 #define CLOCK_DDR DDRC
50 #define RESET_PORT PORTF
51 #define RESET_DDR DDRF
57 // Make sure we haven't overflowed the buffer
58 #define bufferAdd(byte) \
59 if ( KeyIndex_BufferUsed < KEYBOARD_BUFFER ) \
60 KeyIndex_Buffer[KeyIndex_BufferUsed++] = byte
64 // ----- Variables -----
66 // Buffer used to inform the macro processing module which keys have been detected as pressed
67 volatile uint8_t KeyIndex_Buffer[KEYBOARD_BUFFER];
68 volatile uint8_t KeyIndex_BufferUsed;
69 volatile uint8_t KeyIndex_Add_InputSignal; // Used to pass the (click/input value) to the keyboard for the clicker
71 volatile uint8_t currentWaveState = 0;
72 volatile uint8_t positionCounter = 0;
74 volatile uint8_t statePositionCounter = 0;
75 volatile uint16_t stateSamplesTotal = 0;
76 volatile uint16_t stateSamples = 0;
80 volatile uint8_t BufferReadyToClear;
84 // ----- Function Declarations -----
86 void processKeyValue( uint8_t keyValue );
87 void removeKeyValue( uint8_t keyValue );
91 // ----- Interrupt Functions -----
93 // Generates a constant external clock
94 ISR( TIMER1_COMPA_vect )
96 if ( currentWaveState )
98 CLOCK_PORT &= ~(1 << CLOCK_PIN);
99 currentWaveState--; // Keeps track of the clock value (for direct clock output)
100 statePositionCounter = positionCounter;
101 positionCounter++; // Counts the number of falling edges, reset is done by the controlling section (reset, or main scan)
105 CLOCK_PORT |= (1 << CLOCK_PIN);
112 // ----- Functions -----
115 inline void scan_setup()
117 // Setup Timer Pulse (16 bit)
119 // TODO Clock can be adjusted to whatever (read chip datasheets for limits)
120 // This seems like a good scan speed, as there don't seem to be any periodic
121 // de-synchronization events, and is fast enough for scanning keys
122 // Anything much more (100k baud), tends to cause a lot of de-synchronization
123 // 16 MHz / (2 * Prescaler * (1 + OCR1A)) = 10k baud
129 TIMSK1 = (1 << OCIE1A);
131 CLOCK_DDR |= (1 << CLOCK_PIN); // Set the clock pin as an output
132 DATA_PORT |= (1 << DATA_PIN); // Pull-up resistor for input the data line
136 // Initially buffer doesn't need to be cleared (it's empty...)
137 BufferReadyToClear = 0;
139 // Reset the keyboard before scanning, we might be in a wierd state
140 scan_resetKeyboard();
144 // Main Detection Loop
145 // Since this function is non-interruptable, we can do checks here on what stage of the
146 // output clock we are at (0 or 1)
147 // We are looking for a start of packet
148 // If detected, all subsequent bits are then logged into a variable
149 // Once the end of the packet has been detected (always the same length), decode the pressed keys
150 inline uint8_t scan_loop()
152 // Only use as a valid signal
153 // Check if there was a position change
154 if ( positionCounter != statePositionCounter )
156 // At least 80% of the samples must be valid
157 if ( stateSamples * 100 / stateSamplesTotal >= 80 )
159 // Reset the scan counter, all the keys have been iterated over
160 // Ideally this should reset at 128, however
161 // due to noise in the cabling, this often moves around
162 // The minimum this can possibly set to is 124 as there
163 // are keys to service at 123 (0x78)
164 // Usually, unless there is lots of interference,
165 // this should limit most of the noise.
166 if ( positionCounter >= 124 )
170 // Key Press Detected
171 // - Skip 0x00 to 0x0B (11) for better jitter immunity (as there are no keys mapped to those scancodes)
172 else if ( positionCounter > 0x0B )
175 hexToStr( positionCounter, tmp );
176 dPrintStrsNL( "Key: ", tmp );
178 // Make sure there aren't any duplicate keys
180 for ( c = 0; c < KeyIndex_BufferUsed; c++ )
181 if ( KeyIndex_Buffer[c] == positionCounter )
184 // No duplicate keys, add it to the buffer
185 if ( c == KeyIndex_BufferUsed )
186 bufferAdd( positionCounter );
189 // Remove the key from the buffer
190 else if ( positionCounter < 124 && positionCounter > 0x0B )
192 // Check for the released key, and shift the other keys lower on the buffer
194 for ( c = 0; c < KeyIndex_BufferUsed; c++ )
196 // Key to release found
197 if ( KeyIndex_Buffer[c] == positionCounter )
199 // Shift keys from c position
200 for ( uint8_t k = c; k < KeyIndex_BufferUsed - 1; k++ )
201 KeyIndex_Buffer[k] = KeyIndex_Buffer[k + 1];
204 KeyIndex_BufferUsed--;
212 // Clear the state counters
214 stateSamplesTotal = 0;
215 statePositionCounter = positionCounter;
218 // Pull in a data sample for this read instance
219 if ( DATA_OUT & (1 <<DATA_PIN) )
223 // Check if the clock de-synchronized
225 if ( positionCounter > 128 )
228 hexToStr( positionCounter, tmp );
229 erro_dPrint( "De-synchronization detected at: ", tmp );
233 KeyIndex_BufferUsed = 0;
235 // Clear the state counters
237 stateSamplesTotal = 0;
239 // A keyboard reset requires interrupts to be enabled
241 scan_resetKeyboard();
245 // Regardless of what happens, always return 0
250 uint8_t scan_sendData( uint8_t dataPayload )
255 // Signal KeyIndex_Buffer that it has been properly read
256 void scan_finishedWithBuffer( void )
260 // Signal that the keys have been properly sent over USB
261 void scan_finishedWithUSBBuffer( void )
265 // Reset/Hold keyboard
266 // NOTE: Does nothing with the HP150
267 void scan_lockKeyboard( void )
271 // NOTE: Does nothing with the HP150
272 void scan_unlockKeyboard( void )
277 void scan_resetKeyboard( void )
279 info_print("Attempting to synchronize the keyboard, do not press any keys...");
282 // Do a proper keyboard reset (flushes the ripple counters)
283 RESET_PORT |= (1 << RESET_PIN);
285 RESET_PORT &= ~(1 << RESET_PIN);
287 // Delay main keyboard scanning, until the bit counter is synchronized
288 uint8_t synchronized = 0;
289 while ( !synchronized )
291 // Only use as a valid signal
292 // Check if there was a position change
293 if ( positionCounter != statePositionCounter )
295 // At least 80% of the samples must be valid
296 if ( stateSamples * 100 / stateSamplesTotal >= 80 )
298 // Read the current data value
299 if ( DATA_OUT & (1 << DATA_PIN) )
301 // Check if synchronized
302 // There are 128 positions to scan for with the HP150 keyboard protocol
303 if ( positionCounter == 128 )
310 // Clear the state counters
312 stateSamplesTotal = 0;
313 statePositionCounter = positionCounter;
317 info_print("Keyboard Synchronized!");