]> git.donarmstrong.com Git - kiibohd-controller.git/blob - Scan/HP150/scan_loop.c
Adding more robust detection for the HP150
[kiibohd-controller.git] / Scan / HP150 / 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 DATA_PORT PORTC
42 #define DATA_DDR   DDRC
43 #define DATA_PIN      7
44 #define DATA_OUT   PINC
45
46 #define CLOCK_PORT PORTC
47 #define CLOCK_DDR   DDRC
48 #define CLOCK_PIN      6
49
50 #define RESET_PORT PORTF
51 #define RESET_DDR   DDRF
52 #define RESET_PIN      7
53
54
55 // ----- Macros -----
56
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
61
62
63
64 // ----- Variables -----
65
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
70
71 volatile uint8_t currentWaveState = 0;
72 volatile uint8_t positionCounter = 0;
73
74 volatile uint8_t statePositionCounter = 0;
75 volatile uint16_t stateSamplesTotal = 0;
76 volatile uint16_t stateSamples = 0;
77
78
79 // Buffer Signals
80 volatile uint8_t BufferReadyToClear;
81
82
83
84 // ----- Function Declarations -----
85
86 void processKeyValue( uint8_t keyValue );
87 void  removeKeyValue( uint8_t keyValue );
88
89
90
91 // ----- Interrupt Functions -----
92
93 // Generates a constant external clock
94 ISR( TIMER1_COMPA_vect )
95 {
96         if ( currentWaveState )
97         {
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)
102         }
103         else
104         {
105                 CLOCK_PORT |=  (1 << CLOCK_PIN);
106                 currentWaveState++;
107         }
108 }
109
110
111
112 // ----- Functions -----
113
114 // Setup
115 inline void scan_setup()
116 {
117         // Setup Timer Pulse (16 bit)
118
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
124         // Prescaler is 1
125         cli();
126         TCCR1B = 0x09;
127         OCR1AH = 0x03;
128         OCR1AL = 0x1F;
129         TIMSK1 = (1 << OCIE1A);
130
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
133         sei();
134
135
136         // Initially buffer doesn't need to be cleared (it's empty...)
137         BufferReadyToClear = 0;
138
139         // Reset the keyboard before scanning, we might be in a wierd state
140         scan_resetKeyboard();
141 }
142
143
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()
151 {
152         // Only use as a valid signal
153         // Check if there was a position change
154         if ( positionCounter != statePositionCounter )
155         {
156                 // At least 80% of the samples must be valid
157                 if ( stateSamples * 100 / stateSamplesTotal >= 80 )
158                 {
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 )
167                         {
168                                 positionCounter = 0;
169                         }
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 )
173                         {
174                                 char tmp[15];
175                                 hexToStr( positionCounter, tmp );
176                                 dPrintStrsNL( "Key: ", tmp );
177
178                                 // Make sure there aren't any duplicate keys
179                                 uint8_t c;
180                                 for ( c = 0; c < KeyIndex_BufferUsed; c++ )
181                                         if ( KeyIndex_Buffer[c] == positionCounter )
182                                                 break;
183
184                                 // No duplicate keys, add it to the buffer
185                                 if ( c == KeyIndex_BufferUsed )
186                                         bufferAdd( positionCounter );
187                         }
188                 }
189                 // Remove the key from the buffer
190                 else if ( positionCounter < 124 && positionCounter > 0x0B )
191                 {
192                         // Check for the released key, and shift the other keys lower on the buffer
193                         uint8_t c;
194                         for ( c = 0; c < KeyIndex_BufferUsed; c++ )
195                         {
196                                 // Key to release found
197                                 if ( KeyIndex_Buffer[c] == positionCounter )
198                                 {
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];
202
203                                         // Decrement Buffer
204                                         KeyIndex_BufferUsed--;
205
206                                         break;
207                                 }
208                         }
209                 }
210
211
212                 // Clear the state counters
213                 stateSamples = 0;
214                 stateSamplesTotal = 0;
215                 statePositionCounter = positionCounter;
216         }
217
218         // Pull in a data sample for this read instance
219         if ( DATA_OUT & (1 <<DATA_PIN) )
220                 stateSamples++;
221         stateSamplesTotal++;
222
223         // Check if the clock de-synchronized
224         // And reset
225         if ( positionCounter > 128 )
226         {
227                 char tmp[15];
228                 hexToStr( positionCounter, tmp );
229                 erro_dPrint( "De-synchronization detected at: ", tmp );
230                 errorLED( 1 );
231
232                 positionCounter = 0;
233                 KeyIndex_BufferUsed = 0;
234
235                 // Clear the state counters
236                 stateSamples = 0;
237                 stateSamplesTotal = 0;
238
239                 // A keyboard reset requires interrupts to be enabled
240                 sei();
241                 scan_resetKeyboard();
242                 cli();
243         }
244
245         // Regardless of what happens, always return 0
246         return 0;
247 }
248
249 // Send data 
250 uint8_t scan_sendData( uint8_t dataPayload )
251 {
252         return 0;
253 }
254
255 // Signal KeyIndex_Buffer that it has been properly read
256 void scan_finishedWithBuffer( void )
257 {
258 }
259
260 // Signal that the keys have been properly sent over USB
261 void scan_finishedWithUSBBuffer( void )
262 {
263 }
264
265 // Reset/Hold keyboard
266 // NOTE: Does nothing with the HP150
267 void scan_lockKeyboard( void )
268 {
269 }
270
271 // NOTE: Does nothing with the HP150
272 void scan_unlockKeyboard( void )
273 {
274 }
275
276 // Reset Keyboard
277 void scan_resetKeyboard( void )
278 {
279         info_print("Attempting to synchronize the keyboard, do not press any keys...");
280         errorLED( 1 );
281
282         // Do a proper keyboard reset (flushes the ripple counters)
283         RESET_PORT |=  (1 << RESET_PIN);
284         _delay_us(10);
285         RESET_PORT &= ~(1 << RESET_PIN);
286
287         // Delay main keyboard scanning, until the bit counter is synchronized
288         uint8_t synchronized = 0;
289         while ( !synchronized )
290         {
291                 // Only use as a valid signal
292                 // Check if there was a position change
293                 if ( positionCounter != statePositionCounter )
294                 {
295                         // At least 80% of the samples must be valid
296                         if ( stateSamples * 100 / stateSamplesTotal >= 80 )
297                         {
298                                 // Read the current data value
299                                 if ( DATA_OUT & (1 << DATA_PIN) )
300                                 {
301                                         // Check if synchronized
302                                         // There are 128 positions to scan for with the HP150 keyboard protocol
303                                         if ( positionCounter == 128 )
304                                                 synchronized = 1;
305
306                                         positionCounter = 0;
307                                 }
308                         }
309
310                         // Clear the state counters
311                         stateSamples = 0;
312                         stateSamplesTotal = 0;
313                         statePositionCounter = positionCounter;
314                 }
315         }
316
317         info_print("Keyboard Synchronized!");
318 }
319