]> git.donarmstrong.com Git - kiibohd-controller.git/blob - Scan/HP150/scan_loop.c
Completing the HP150 converter.
[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 currentWaveDone = 0;
73 volatile uint8_t positionCounter = 0;
74
75
76 // Buffer Signals
77 volatile uint8_t BufferReadyToClear;
78
79
80
81 // ----- Function Declarations -----
82
83 void processKeyValue( uint8_t keyValue );
84 void  removeKeyValue( uint8_t keyValue );
85
86
87
88 // ----- Interrupt Functions -----
89
90 // Generates a constant external clock
91 ISR( TIMER1_COMPA_vect )
92 {
93         if ( currentWaveState )
94         {
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)
99         }
100         else
101         {
102                 CLOCK_PORT |=  (1 << CLOCK_PIN);
103                 currentWaveState++;
104         }
105 }
106
107
108
109 // ----- Functions -----
110
111 // Setup
112 inline void scan_setup()
113 {
114         // Setup Timer Pulse (16 bit)
115
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
121         // Prescaler is 1
122         cli();
123         TCCR1B = 0x09;
124         OCR1AH = 0x03;
125         OCR1AL = 0x1F;
126         TIMSK1 = (1 << OCIE1A);
127         CLOCK_DDR = (1 << CLOCK_PIN);
128         sei();
129
130
131         // Initially buffer doesn't need to be cleared (it's empty...)
132         BufferReadyToClear = 0;
133
134         // Reset the keyboard before scanning, we might be in a wierd state
135         scan_resetKeyboard();
136 }
137
138
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()
146 {
147         // Read on each falling edge/after the falling edge of the clock
148         if ( !currentWaveDone )
149         {
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)
157                 uint8_t total = 0;
158                 uint8_t c = 0;
159                 for ( ; c < 50; c++ )
160                         if ( DATA_OUT & (1 << DATA_PIN) )
161                                 total++;
162
163
164                 // Only use as a valid signal
165                 if ( total >= 40 )
166                 {
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 )
175                         {
176                                 positionCounter = 0;
177
178                                 // Clear key buffer
179                                 KeyIndex_BufferUsed = 0;
180                         }
181                         // Key Press Detected
182                         else
183                         {
184                                 char tmp[15];
185                                 hexToStr( positionCounter, tmp );
186                                 dPrintStrsNL( "Key: ", tmp );
187
188                                 bufferAdd( positionCounter );
189                         }
190                 }
191
192                 // Wait until the next falling clock edge for the next DATA scan
193                 currentWaveDone++;
194         }
195
196         // Check if the clock de-synchronized
197         // And reset
198         if ( positionCounter > 128 )
199         {
200                 char tmp[15];
201                 hexToStr( positionCounter, tmp );
202                 erro_dPrint( "De-synchronization detected at: ", tmp );
203                 errorLED( 1 );
204
205                 positionCounter = 0;
206                 KeyIndex_BufferUsed = 0;
207
208                 // A keyboard reset requires interrupts to be enabled
209                 sei();
210                 scan_resetKeyboard();
211                 cli();
212         }
213
214         // Regardless of what happens, always return 0
215         return 0;
216 }
217
218 // Send data 
219 uint8_t scan_sendData( uint8_t dataPayload )
220 {
221         return 0;
222 }
223
224 // Signal KeyIndex_Buffer that it has been properly read
225 void scan_finishedWithBuffer( void )
226 {
227 }
228
229 // Signal that the keys have been properly sent over USB
230 void scan_finishedWithUSBBuffer( void )
231 {
232 }
233
234 // Reset/Hold keyboard
235 // NOTE: Does nothing with the HP150
236 void scan_lockKeyboard( void )
237 {
238 }
239
240 // NOTE: Does nothing with the HP150
241 void scan_unlockKeyboard( void )
242 {
243 }
244
245 // Reset Keyboard
246 void scan_resetKeyboard( void )
247 {
248         info_print("Attempting to synchronize the keyboard, do not press any keys...");
249         errorLED( 1 );
250
251         // Do a proper keyboard reset (flushes the ripple counters)
252         RESET_PORT |=  (1 << RESET_PIN);
253         _delay_us(10);
254         RESET_PORT &= ~(1 << RESET_PIN);
255
256         // Delay main keyboard scanning, until the bit counter is synchronized
257         uint8_t synchronized = 0;
258         while ( !synchronized )
259         {
260                 // Read on each falling edge/after the falling edge of the clock
261                 if ( !currentWaveDone )
262                 {
263                         // Read the current data value
264                         if ( DATA_OUT & (1 << DATA_PIN) )
265                         {
266                                 // Check if synchronized
267                                 // There are 128 positions to scan for with the HP150 keyboard protocol
268                                 if ( positionCounter == 128 )
269                                         synchronized = 1;
270
271                                 positionCounter = 0;
272                         }
273
274                         // Wait until the next falling clock edge for the next DATA scan
275                         currentWaveDone++;
276                 }
277         }
278
279         info_print("Keyboard Synchronized!");
280 }
281