]> git.donarmstrong.com Git - kiibohd-controller.git/blob - Scan/HP150/scan_loop.c
Major code cleanup and preparation for PartialMap Macro Module
[kiibohd-controller.git] / Scan / HP150 / scan_loop.c
1 /* Copyright (C) 2012,2014 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 // Compiler Includes
25 #include <Lib/ScanLib.h>
26
27 // Project Includes
28 #include <led.h>
29 #include <print.h>
30
31 // Local Includes
32 #include "scan_loop.h"
33
34
35
36 // ----- Defines -----
37
38 // Pinout Defines
39 #define DATA_PORT PORTC
40 #define DATA_DDR   DDRC
41 #define DATA_PIN      7
42 #define DATA_OUT   PINC
43
44 #define CLOCK_PORT PORTC
45 #define CLOCK_DDR   DDRC
46 #define CLOCK_PIN      6
47
48 #define RESET_PORT PORTF
49 #define RESET_DDR   DDRF
50 #define RESET_PIN      7
51
52
53 // ----- Macros -----
54
55
56
57 // ----- Variables -----
58
59 // Buffer used to inform the macro processing module which keys have been detected as pressed
60 volatile uint8_t KeyIndex_Buffer[KEYBOARD_BUFFER];
61 volatile uint8_t KeyIndex_BufferUsed;
62 volatile uint8_t KeyIndex_Add_InputSignal; // Used to pass the (click/input value) to the keyboard for the clicker
63
64 volatile uint8_t currentWaveState = 0;
65 volatile uint8_t positionCounter = 0;
66
67 volatile uint8_t statePositionCounter = 0;
68 volatile uint16_t stateSamplesTotal = 0;
69 volatile uint16_t stateSamples = 0;
70
71
72 // Buffer Signals
73 volatile uint8_t BufferReadyToClear;
74
75
76
77 // ----- Function Declarations -----
78
79 void processKeyValue( uint8_t keyValue );
80 void  removeKeyValue( uint8_t keyValue );
81
82
83
84 // ----- Interrupt Functions -----
85
86 // Generates a constant external clock
87 ISR( TIMER1_COMPA_vect )
88 {
89         if ( currentWaveState )
90         {
91                 CLOCK_PORT &= ~(1 << CLOCK_PIN);
92                 currentWaveState--; // Keeps track of the clock value (for direct clock output)
93                 statePositionCounter = positionCounter;
94                 positionCounter++;  // Counts the number of falling edges, reset is done by the controlling section (reset, or main scan)
95         }
96         else
97         {
98                 CLOCK_PORT |=  (1 << CLOCK_PIN);
99                 currentWaveState++;
100         }
101 }
102
103
104
105 // ----- Functions -----
106
107 // Setup
108 inline void Scan_setup()
109 {
110         // Setup Timer Pulse (16 bit)
111
112         // TODO Clock can be adjusted to whatever (read chip datasheets for limits)
113         // This seems like a good scan speed, as there don't seem to be any periodic
114         //  de-synchronization events, and is fast enough for scanning keys
115         // Anything much more (100k baud), tends to cause a lot of de-synchronization
116         // 16 MHz / (2 * Prescaler * (1 + OCR1A)) = 10k baud
117         // Prescaler is 1
118         cli();
119         TCCR1B = 0x09;
120         OCR1AH = 0x03;
121         OCR1AL = 0x1F;
122         TIMSK1 = (1 << OCIE1A);
123
124         CLOCK_DDR |= (1 << CLOCK_PIN); // Set the clock pin as an output
125         DATA_PORT |= (1 << DATA_PIN);  // Pull-up resistor for input the data line
126         sei();
127
128
129         // Initially buffer doesn't need to be cleared (it's empty...)
130         BufferReadyToClear = 0;
131
132         // Reset the keyboard before scanning, we might be in a wierd state
133         scan_resetKeyboard();
134 }
135
136
137 // Main Detection Loop
138 // Since this function is non-interruptable, we can do checks here on what stage of the
139 //  output clock we are at (0 or 1)
140 // We are looking for a start of packet
141 // If detected, all subsequent bits are then logged into a variable
142 // Once the end of the packet has been detected (always the same length), decode the pressed keys
143 inline uint8_t Scan_loop()
144 {
145         // Only use as a valid signal
146         // Check if there was a position change
147         if ( positionCounter != statePositionCounter )
148         {
149                 // At least 80% of the samples must be valid
150                 if ( stateSamples * 100 / stateSamplesTotal >= 80 )
151                 {
152                         // Reset the scan counter, all the keys have been iterated over
153                         // Ideally this should reset at 128, however
154                         //  due to noise in the cabling, this often moves around
155                         // The minimum this can possibly set to is 124 as there
156                         //  are keys to service at 123 (0x78)
157                         // Usually, unless there is lots of interference,
158                         //  this should limit most of the noise.
159                         if ( positionCounter >= 124 )
160                         {
161                                 positionCounter = 0;
162                         }
163                         // Key Press Detected
164                         //  - Skip 0x00 to 0x0B (11) for better jitter immunity (as there are no keys mapped to those scancodes)
165                         else if ( positionCounter > 0x0B )
166                         {
167                                 char tmp[15];
168                                 hexToStr( positionCounter, tmp );
169                                 dPrintStrsNL( "Key: ", tmp );
170
171                                 // Make sure there aren't any duplicate keys
172                                 uint8_t c;
173                                 for ( c = 0; c < KeyIndex_BufferUsed; c++ )
174                                         if ( KeyIndex_Buffer[c] == positionCounter )
175                                                 break;
176
177                                 // No duplicate keys, add it to the buffer
178                                 if ( c == KeyIndex_BufferUsed )
179                                         Macro_bufferAdd( positionCounter );
180                         }
181                 }
182                 // Remove the key from the buffer
183                 else if ( positionCounter < 124 && positionCounter > 0x0B )
184                 {
185                         // Check for the released key, and shift the other keys lower on the buffer
186                         uint8_t c;
187                         for ( c = 0; c < KeyIndex_BufferUsed; c++ )
188                         {
189                                 // Key to release found
190                                 if ( KeyIndex_Buffer[c] == positionCounter )
191                                 {
192                                         // Shift keys from c position
193                                         for ( uint8_t k = c; k < KeyIndex_BufferUsed - 1; k++ )
194                                                 KeyIndex_Buffer[k] = KeyIndex_Buffer[k + 1];
195
196                                         // Decrement Buffer
197                                         KeyIndex_BufferUsed--;
198
199                                         break;
200                                 }
201                         }
202                 }
203
204
205                 // Clear the state counters
206                 stateSamples = 0;
207                 stateSamplesTotal = 0;
208                 statePositionCounter = positionCounter;
209         }
210
211         // Pull in a data sample for this read instance
212         if ( DATA_OUT & (1 <<DATA_PIN) )
213                 stateSamples++;
214         stateSamplesTotal++;
215
216         // Check if the clock de-synchronized
217         // And reset
218         if ( positionCounter > 128 )
219         {
220                 char tmp[15];
221                 hexToStr( positionCounter, tmp );
222                 erro_dPrint( "De-synchronization detected at: ", tmp );
223                 errorLED( 1 );
224
225                 positionCounter = 0;
226                 KeyIndex_BufferUsed = 0;
227
228                 // Clear the state counters
229                 stateSamples = 0;
230                 stateSamplesTotal = 0;
231
232                 // A keyboard reset requires interrupts to be enabled
233                 sei();
234                 scan_resetKeyboard();
235                 cli();
236         }
237
238         // Regardless of what happens, always return 0
239         return 0;
240 }
241
242 // Send data 
243 uint8_t Scan_sendData( uint8_t dataPayload )
244 {
245         return 0;
246 }
247
248 // Signal KeyIndex_Buffer that it has been properly read
249 void Scan_finishedWithBuffer( uint8_t sentKeys )
250 {
251 }
252
253 // Signal that the keys have been properly sent over USB
254 void Scan_finishedWithUSBBuffer( uint8_t sentKeys )
255 {
256 }
257
258 // Reset/Hold keyboard
259 // NOTE: Does nothing with the HP150
260 void Scan_lockKeyboard( void )
261 {
262 }
263
264 // NOTE: Does nothing with the HP150
265 void Scan_unlockKeyboard( void )
266 {
267 }
268
269 // Reset Keyboard
270 void Scan_resetKeyboard( void )
271 {
272         info_print("Attempting to synchronize the keyboard, do not press any keys...");
273         errorLED( 1 );
274
275         // Do a proper keyboard reset (flushes the ripple counters)
276         RESET_PORT |=  (1 << RESET_PIN);
277         _delay_us(10);
278         RESET_PORT &= ~(1 << RESET_PIN);
279
280         // Delay main keyboard scanning, until the bit counter is synchronized
281         uint8_t synchronized = 0;
282         while ( !synchronized )
283         {
284                 // Only use as a valid signal
285                 // Check if there was a position change
286                 if ( positionCounter != statePositionCounter )
287                 {
288                         // At least 80% of the samples must be valid
289                         if ( stateSamples * 100 / stateSamplesTotal >= 80 )
290                         {
291                                 // Read the current data value
292                                 if ( DATA_OUT & (1 << DATA_PIN) )
293                                 {
294                                         // Check if synchronized
295                                         // There are 128 positions to scan for with the HP150 keyboard protocol
296                                         if ( positionCounter == 128 )
297                                                 synchronized = 1;
298
299                                         positionCounter = 0;
300                                 }
301                         }
302
303                         // Clear the state counters
304                         stateSamples = 0;
305                         stateSamplesTotal = 0;
306                         statePositionCounter = positionCounter;
307                 }
308         }
309
310         info_print("Keyboard Synchronized!");
311 }
312