]> git.donarmstrong.com Git - tmk_firmware.git/blob - protocol/adb.c
Fix ADB missing keystrokes problem Thanks, blargg! #14
[tmk_firmware.git] / protocol / adb.c
1 /*
2 Copyright 2011 Jun WAKO <wakojun@gmail.com>
3
4 This software is licensed with a Modified BSD License.
5 All of this is supposed to be Free Software, Open Source, DFSG-free,
6 GPL-compatible, and OK to use in both free and proprietary applications.
7 Additions and corrections to this file are welcome.
8
9
10 Redistribution and use in source and binary forms, with or without
11 modification, are permitted provided that the following conditions are met:
12
13 * Redistributions of source code must retain the above copyright
14   notice, this list of conditions and the following disclaimer.
15
16 * Redistributions in binary form must reproduce the above copyright
17   notice, this list of conditions and the following disclaimer in
18   the documentation and/or other materials provided with the
19   distribution.
20
21 * Neither the name of the copyright holders nor the names of
22   contributors may be used to endorse or promote products derived
23   from this software without specific prior written permission.
24
25 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
26 AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
27 IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
28 ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
29 LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
30 CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
31 SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
32 INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
33 CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
34 ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
35 POSSIBILITY OF SUCH DAMAGE.
36 */
37
38 #include <stdbool.h>
39 #include <util/delay.h>
40 #include <avr/io.h>
41 #include <avr/interrupt.h>
42 #include "adb.h"
43 #include "debug.h"
44
45
46 static inline void data_lo(void);
47 static inline void data_hi(void);
48 static inline bool data_in(void);
49 #ifdef ADB_PSW_BIT
50 static inline void psw_lo(void);
51 static inline void psw_hi(void);
52 static inline bool psw_in(void);
53 #endif
54
55 static inline void attention(void);
56 static inline void place_bit0(void);
57 static inline void place_bit1(void);
58 static inline void send_byte(uint8_t data);
59 static inline bool read_bit(void);
60 static inline uint8_t read_byte(void);
61 static inline uint8_t wait_data_lo(uint16_t us);
62 static inline uint8_t wait_data_hi(uint8_t us);
63
64
65 void adb_host_init(void)
66 {
67     data_hi();
68 #ifdef ADB_PSW_BIT
69     psw_hi();
70 #endif
71
72     // Enable keyboard left/right modifier distinction
73     // Addr:Keyboard(0010), Cmd:Listen(10), Register3(11)
74     // upper byte: reserved bits 0000, device address 0010
75     // lower byte: device handler 00000011
76     adb_host_listen(0x2B,0x02,0x03);
77 }
78
79 #ifdef ADB_PSW_BIT
80 bool adb_host_psw(void)
81 {
82     return psw_in();
83 }
84 #endif
85
86 /*
87  * Don't call this in a row without the delay, otherwise it makes some of poor controllers
88  * overloaded and misses strokes. Recommended delay is 16ms.
89  *
90  * Thanks a lot, blargg! <http://geekhack.org/index.php?topic=14290.msg1068919#msg1068919>
91  */
92 uint16_t adb_host_kbd_recv(void)
93 {
94     uint16_t data = 0;
95     attention();
96     send_byte(0x2C);            // Addr:Keyboard(0010), Cmd:Talk(11), Register0(00)
97     place_bit0();               // Stopbit(0)
98     if (!wait_data_lo(500)) {   // Tlt/Stop to Start(140-260us)
99         return 0;               // No data to send
100     }
101     if (!read_bit()) {          // Startbit(1)
102         // Service Request
103         dprintf("Startbit ERROR\n");
104         return -2;
105     }
106
107     // ad hoc fix: without block inerrupt read wrong bit occasionally and get keys stuck
108     cli();
109     data = read_byte();
110     data = (data<<8) | read_byte();
111     uint8_t stop = read_bit();  // Stopbit(0)
112     sei();
113
114     if (stop) {
115         dprintf("Stopbit ERROR\n");
116         return -3;
117     }
118     return data;
119 }
120
121 void adb_host_listen(uint8_t cmd, uint8_t data_h, uint8_t data_l)
122 {
123     attention();
124     send_byte(cmd);
125     place_bit0();               // Stopbit(0)
126     _delay_us(200);             // Tlt/Stop to Start
127     place_bit1();               // Startbit(1)
128     send_byte(data_h); 
129     send_byte(data_l);
130     place_bit0();               // Stopbit(0);
131 }
132
133 // send state of LEDs
134 void adb_host_kbd_led(uint8_t led)
135 {
136     // Addr:Keyboard(0010), Cmd:Listen(10), Register2(10)
137     // send upper byte (not used)
138     // send lower byte (bit2: ScrollLock, bit1: CapsLock, bit0:
139     adb_host_listen(0x2A,0,led&0x07);
140 }
141
142
143 static inline void data_lo()
144 {
145     ADB_DDR  |=  (1<<ADB_DATA_BIT);
146     ADB_PORT &= ~(1<<ADB_DATA_BIT);
147 }
148 static inline void data_hi()
149 {
150     ADB_PORT |=  (1<<ADB_DATA_BIT);
151     ADB_DDR  &= ~(1<<ADB_DATA_BIT);
152 }
153 static inline bool data_in()
154 {
155     ADB_PORT |=  (1<<ADB_DATA_BIT);
156     ADB_DDR  &= ~(1<<ADB_DATA_BIT);
157     return ADB_PIN&(1<<ADB_DATA_BIT);
158 }
159
160 #ifdef ADB_PSW_BIT
161 static inline void psw_lo()
162 {
163     ADB_DDR  |=  (1<<ADB_PSW_BIT);
164     ADB_PORT &= ~(1<<ADB_PSW_BIT);
165 }
166 static inline void psw_hi()
167 {
168     ADB_PORT |=  (1<<ADB_PSW_BIT);
169     ADB_DDR  &= ~(1<<ADB_PSW_BIT);
170 }
171 static inline bool psw_in()
172 {
173     ADB_PORT |=  (1<<ADB_PSW_BIT);
174     ADB_DDR  &= ~(1<<ADB_PSW_BIT);
175     return ADB_PIN&(1<<ADB_PSW_BIT);
176 }
177 #endif
178
179 static inline void attention(void)
180 {
181     data_lo();
182     _delay_us(700);
183     place_bit1();
184 }
185
186 static inline void place_bit0(void)
187 {
188     data_lo();
189     _delay_us(65);
190     data_hi();
191     _delay_us(35);
192 }
193
194 static inline void place_bit1(void)
195 {
196     data_lo();
197     _delay_us(35);
198     data_hi();
199     _delay_us(65);
200 }
201
202 static inline void send_byte(uint8_t data)
203 {
204     for (int i = 0; i < 8; i++) {
205         if (data&(0x80>>i))
206             place_bit1();
207         else
208             place_bit0();
209     }
210 }
211
212 static inline bool read_bit(void)
213 {
214     // ADB Bit Cells
215     //
216     // bit cell time: 70-130us
217     // low part of bit0: 60-70% of bit cell
218     // low part of bit1: 30-40% of bit cell
219     //
220     //    bit cell time         70us        130us
221     //    --------------------------------------------
222     //    low  part of bit0     42-49       78-91
223     //    high part of bit0     21-28       39-52
224     //    low  part of bit1     21-28       39-52
225     //    high part of bit1     42-49       78-91
226     //
227     //
228     // bit0:
229     //    70us bit cell:
230     //      ____________~~~~~~
231     //      42-49        21-28  
232     //
233     //    130us bit cell:
234     //      ____________~~~~~~
235     //      78-91        39-52  
236     //
237     // bit1:
238     //    70us bit cell:
239     //      ______~~~~~~~~~~~~
240     //      21-28        42-49
241     //
242     //    130us bit cell:
243     //      ______~~~~~~~~~~~~
244     //      39-52        78-91
245     //
246     // read:
247     //      ________|~~~~~~~~~
248     //              55us
249     // Read data line after 55us. If data line is low/high then bit is 0/1.
250     // This method might not work at <90us bit cell time.
251     //
252     // [from Apple IIgs Hardware Reference Second Edition]
253     bool bit;
254     wait_data_lo(75);   // wait the start of bit cell at least 130ms(55+0+75)
255     _delay_us(55);
256     bit = data_in();
257     wait_data_hi(36);   // wait high part of bit cell at least 91ms(55+36)
258     return bit;
259 }
260
261 static inline uint8_t read_byte(void)
262 {
263     uint8_t data = 0;
264     for (int i = 0; i < 8; i++) {
265         data <<= 1;
266         if (read_bit())
267             data = data | 1;
268     }
269     return data;
270 }
271
272 static inline uint8_t wait_data_lo(uint16_t us)
273 {
274     while (data_in() && us) {
275         _delay_us(1);
276         us--;
277     }
278     return us;
279 }
280
281 static inline uint8_t wait_data_hi(uint8_t us)
282 {
283     while (!data_in() && us) {
284         _delay_us(1);
285         us--;
286     }
287     return us;
288 }
289
290
291 /*
292 ADB Protocol
293 ============
294
295 Resources
296 ---------
297 ADB - The Untold Story: Space Aliens Ate My Mouse
298     http://developer.apple.com/legacy/mac/library/#technotes/hw/hw_01.html
299 ADB Manager
300     http://developer.apple.com/legacy/mac/library/documentation/mac/pdf/Devices/ADB_Manager.pdf
301     Service request(5-17)
302 Apple IIgs Hardware Reference Second Edition [Chapter6 p121]
303     ftp://ftp.apple.asimov.net/pub/apple_II/documentation/Apple%20IIgs%20Hardware%20Reference.pdf
304 ADB Keycode
305     http://72.0.193.250/Documentation/macppc/adbkeycodes/
306     http://m0115.web.fc2.com/m0115.jpg
307     [Inside Macintosh volume V, pages 191-192]
308     http://www.opensource.apple.com/source/IOHIDFamily/IOHIDFamily-421.18.3/IOHIDFamily/Cosmo_USB2ADB.c
309 ADB Signaling
310     http://kbdbabel.sourceforge.net/doc/kbd_signaling_pcxt_ps2_adb.pdf
311 ADB Overview & History
312     http://en.wikipedia.org/wiki/Apple_Desktop_Bus
313 Microchip Application Note: ADB device(with code for PIC16C)
314     http://www.microchip.com/stellent/idcplg?IdcService=SS_GET_PAGE&nodeId=1824&appnote=en011062
315 AVR ATtiny2131 ADB to PS/2 converter(Japanese)
316     http://hp.vector.co.jp/authors/VA000177/html/KeyBoardA5DEA5CBA5A2II.html
317
318
319 Pinouts
320 -------
321     ADB female socket from the front:
322     __________
323     |        | <--- top
324     | 4o  o3 |
325     |2o    o1|
326     |   ==   |
327     |________| <--- bottom
328       |    |   <--- 4pins
329
330
331     ADB female socket from bottom:
332
333     ========== <--- front
334     |        |
335     |        |
336     |2o    o1|
337     |4o    o3|
338     ---------- <--- back
339
340     1: Data
341     2: Power SW(low when press Power key)
342     3: Vcc(5V)
343     4: GND
344
345
346 Commands
347 --------
348     ADB command is 1byte and consists of 4bit-address, 2bit-command
349     type and 2bit-register. The commands are always sent by Host.
350
351     Command format:
352     7 6 5 4 3 2 1 0
353     | | | |------------ address
354             | |-------- command type
355                 | |---- register
356
357     bits                commands
358     ------------------------------------------------------
359     - - - - 0 0 0 0     Send Request(reset all devices)
360     A A A A 0 0 0 1     Flush(reset a device)
361     - - - - 0 0 1 0     Reserved
362     - - - - 0 0 1 1     Reserved
363     - - - - 0 1 - -     Reserved
364     A A A A 1 0 R R     Listen(write to a device)
365     A A A A 1 1 R R     Talk(read from a device)
366
367     The command to read keycodes from keyboard is 0x2C which
368     consist of keyboard address 2 and Talk against register 0. 
369
370     Address:
371     2:  keyboard
372     3:  mice
373
374     Registers:
375     0: application(keyobard uses this to store its data.)
376     1: application
377     2: application(keyboard uses this for LEDs and state of modifiers)
378     3: status and command
379
380
381 Communication
382 -------------
383     This is a minimum information for keyboard communication.
384     See "Resources" for detail.
385
386     Signaling:
387
388     ~~~~____________~~||||||||||||__~~~~~_~~|||||||||||||||__~~~~
389
390         |800us     |  |7 Command 0|  |   |  |15-64  Data  0|Stopbit(0)
391         +Attention |              |  |   +Startbit(1)
392                    +Startbit(1)   |  +Tlt(140-260us)
393                                   +stopbit(0)
394
395     Bit cells:
396
397     bit0: ______~~~
398           65    :35us
399
400     bit1: ___~~~~~~
401           35 :65us
402
403     bit0 low time: 60-70% of bit cell(42-91us)
404     bit1 low time: 30-40% of bit cell(21-52us)
405     bit cell time: 70-130us
406     [from Apple IIgs Hardware Reference Second Edition]
407
408     Criterion for bit0/1:
409     After 55us if line is low/high then bit is 0/1.
410
411     Attention & start bit:
412     Host asserts low in 560-1040us then places start bit(1).
413
414     Tlt(Stop to Start):
415     Bus stays high in 140-260us then device places start bit(1).
416
417     Global reset:
418     Host asserts low in 2.8-5.2ms. All devices are forced to reset.
419
420     Service request from device(Srq):
421     Device can request to send at commad(Global only?) stop bit.
422     Requesting device keeps low for 140-260us at stop bit of command.
423
424
425 Keyboard Data(Register0)
426     This 16bit data can contains two keycodes and two released flags.
427     First keycode is palced in upper byte. When one keyocode is sent,
428     lower byte is 0xFF.
429     Release flag is 1 when key is released.
430
431     1514 . . . . . 8 7 6 . . . . . 0
432      | | | | | | | | | +-+-+-+-+-+-+-   Keycode2
433      | | | | | | | | +---------------   Released2(1 when the key is released)
434      | +-+-+-+-+-+-+-----------------   Keycode1
435      +-------------------------------   Released1(1 when the key is released)
436
437     Keycodes:
438     Scancode consists of 7bit keycode and 1bit release flag.
439     Device can send two keycodes at once. If just one keycode is sent
440     keycode1 contains it and keyocode2 is 0xFF.
441
442     Power switch:
443     You can read the state from PSW line(active low) however
444     the switch has a special scancode 0x7F7F, so you can
445     also read from Data line. It uses 0xFFFF for release scancode.
446
447 Keyboard LEDs & state of keys(Register2)
448     This register hold current state of three LEDs and nine keys.
449     The state of LEDs can be changed by sending Listen command.
450     
451     1514 . . . . . . 7 6 5 . 3 2 1 0
452      | | | | | | | | | | | | | | | +-   LED1(NumLock)
453      | | | | | | | | | | | | | | +---   LED2(CapsLock)
454      | | | | | | | | | | | | | +-----   LED3(ScrollLock)
455      | | | | | | | | | | +-+-+-------   Reserved
456      | | | | | | | | | +-------------   ScrollLock
457      | | | | | | | | +---------------   NumLock
458      | | | | | | | +-----------------   Apple/Command
459      | | | | | | +-------------------   Option
460      | | | | | +---------------------   Shift
461      | | | | +-----------------------   Control
462      | | | +-------------------------   Reset/Power
463      | | +---------------------------   CapsLock
464      | +-----------------------------   Delete
465      +-------------------------------   Reserved
466
467 END_OF_ADB
468 */