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