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 currentWaveDone = 0;
73 volatile uint8_t positionCounter = 0;
77 volatile uint8_t BufferReadyToClear;
81 // ----- Function Declarations -----
83 void processKeyValue( uint8_t keyValue );
84 void removeKeyValue( uint8_t keyValue );
88 // ----- Interrupt Functions -----
90 // Generates a constant external clock
91 ISR( TIMER1_COMPA_vect )
93 if ( currentWaveState )
95 CLOCK_PORT &= ~(1 << CLOCK_PIN);
96 currentWaveState--; // Keeps track of the clock value (for direct clock output)
97 currentWaveDone--; // Keeps track of whether the current falling edge has been processed
98 positionCounter++; // Counts the number of falling edges, reset is done by the controlling section (reset, or main scan)
102 CLOCK_PORT |= (1 << CLOCK_PIN);
109 // ----- Functions -----
112 inline void scan_setup()
114 // Setup Timer Pulse (16 bit)
116 // TODO Clock can be adjusted to whatever (read chip datasheets for limits)
117 // This seems like a good scan speed, as there don't seem to be any periodic
118 // de-synchronization events, and is fast enough for scanning keys
119 // Anything much more (100k baud), tends to cause a lot of de-synchronization
120 // 16 MHz / (2 * Prescaler * (1 + OCR1A)) = 10k baud
126 TIMSK1 = (1 << OCIE1A);
127 CLOCK_DDR = (1 << CLOCK_PIN);
131 // Initially buffer doesn't need to be cleared (it's empty...)
132 BufferReadyToClear = 0;
134 // Reset the keyboard before scanning, we might be in a wierd state
135 scan_resetKeyboard();
139 // Main Detection Loop
140 // Since this function is non-interruptable, we can do checks here on what stage of the
141 // output clock we are at (0 or 1)
142 // We are looking for a start of packet
143 // If detected, all subsequent bits are then logged into a variable
144 // Once the end of the packet has been detected (always the same length), decode the pressed keys
145 inline uint8_t scan_loop()
147 // Read on each falling edge/after the falling edge of the clock
148 if ( !currentWaveDone )
150 // Sample the current value 50 times
151 // If there is a signal for 40/50 of the values, then it is active
152 // This works as a very simple debouncing mechanism
153 // XXX Could be done more intelligently:
154 // Take into account the frequency of the clock + overhead, and space out the reads
155 // Or do something like "dual edge" statistics, where you query the stats from both rising and falling edges
156 // then make a decision (probably won't do much better against the last source of noise, but would do well for debouncing)
159 for ( ; c < 50; c++ )
160 if ( DATA_OUT & (1 << DATA_PIN) )
164 // Only use as a valid signal
167 // Reset the scan counter, all the keys have been iterated over
168 // Ideally this should reset at 128, however
169 // due to noise in the cabling, this often moves around
170 // The minimum this can possibly set to is 124 as there
171 // are keys to service at 123 (0x78)
172 // Usually, unless there is lots of interference,
173 // this should limit most of the noise.
174 if ( positionCounter >= 124 )
179 KeyIndex_BufferUsed = 0;
181 // Key Press Detected
185 hexToStr( positionCounter, tmp );
186 dPrintStrsNL( "Key: ", tmp );
188 bufferAdd( positionCounter );
192 // Wait until the next falling clock edge for the next DATA scan
196 // Check if the clock de-synchronized
198 if ( positionCounter > 128 )
201 hexToStr( positionCounter, tmp );
202 erro_dPrint( "De-synchronization detected at: ", tmp );
206 KeyIndex_BufferUsed = 0;
208 // A keyboard reset requires interrupts to be enabled
210 scan_resetKeyboard();
214 // Regardless of what happens, always return 0
219 uint8_t scan_sendData( uint8_t dataPayload )
224 // Signal KeyIndex_Buffer that it has been properly read
225 void scan_finishedWithBuffer( void )
229 // Signal that the keys have been properly sent over USB
230 void scan_finishedWithUSBBuffer( void )
234 // Reset/Hold keyboard
235 // NOTE: Does nothing with the HP150
236 void scan_lockKeyboard( void )
240 // NOTE: Does nothing with the HP150
241 void scan_unlockKeyboard( void )
246 void scan_resetKeyboard( void )
248 info_print("Attempting to synchronize the keyboard, do not press any keys...");
251 // Do a proper keyboard reset (flushes the ripple counters)
252 RESET_PORT |= (1 << RESET_PIN);
254 RESET_PORT &= ~(1 << RESET_PIN);
256 // Delay main keyboard scanning, until the bit counter is synchronized
257 uint8_t synchronized = 0;
258 while ( !synchronized )
260 // Read on each falling edge/after the falling edge of the clock
261 if ( !currentWaveDone )
263 // Read the current data value
264 if ( DATA_OUT & (1 << DATA_PIN) )
266 // Check if synchronized
267 // There are 128 positions to scan for with the HP150 keyboard protocol
268 if ( positionCounter == 128 )
274 // Wait until the next falling clock edge for the next DATA scan
279 info_print("Keyboard Synchronized!");