]> git.armaanb.net Git - atreides.git/blob - firmware/usb_keyboard.c
Add C firmware.
[atreides.git] / firmware / usb_keyboard.c
1 /* USB Keyboard Example for Teensy USB Development Board
2  * http://www.pjrc.com/teensy/usb_keyboard.html
3  * Copyright (c) 2009 PJRC.COM, LLC
4  *
5  * Permission is hereby granted, free of charge, to any person obtaining a copy
6  * of this software and associated documentation files (the "Software"), to deal
7  * in the Software without restriction, including without limitation the rights
8  * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9  * copies of the Software, and to permit persons to whom the Software is
10  * furnished to do so, subject to the following conditions:
11  *
12  * The above copyright notice and this permission notice shall be included in
13  * all copies or substantial portions of the Software.
14  *
15  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18  * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20  * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21  * THE SOFTWARE.
22  */
23
24 // Version 1.0: Initial Release
25 // Version 1.1: Add support for Teensy 2.0
26
27 #define USB_SERIAL_PRIVATE_INCLUDE
28 #include "usb_keyboard.h"
29
30 /**************************************************************************
31  *
32  *  Configurable Options
33  *
34  **************************************************************************/
35
36 // You can change these to give your code its own name.
37 #define STR_MANUFACTURER    L"Technomancy"
38 #define STR_PRODUCT         L"Orestes"
39
40
41 // Mac OS-X and Linux automatically load the correct drivers.  On
42 // Windows, even though the driver is supplied by Microsoft, an
43 // INF file is needed to load the driver.  These numbers need to
44 // match the INF file.
45 #define VENDOR_ID       0x16C0
46 #define PRODUCT_ID      0x047C
47
48
49 // USB devices are supposed to implment a halt feature, which is
50 // rarely (if ever) used.  If you comment this line out, the halt
51 // code will be removed, saving 102 bytes of space (gcc 4.3.0).
52 // This is not strictly USB compliant, but works with all major
53 // operating systems.
54 #define SUPPORT_ENDPOINT_HALT
55
56
57
58 /**************************************************************************
59  *
60  *  Endpoint Buffer Configuration
61  *
62  **************************************************************************/
63
64 #define ENDPOINT0_SIZE      32
65
66 #define KEYBOARD_INTERFACE  0
67 #define KEYBOARD_ENDPOINT   3
68 #define KEYBOARD_SIZE       8
69 #define KEYBOARD_BUFFER     EP_DOUBLE_BUFFER
70
71 static const uint8_t PROGMEM endpoint_config_table[] = {
72   0,
73   0,
74   1, EP_TYPE_INTERRUPT_IN,  EP_SIZE(KEYBOARD_SIZE) | KEYBOARD_BUFFER,
75   0
76 };
77
78
79 /**************************************************************************
80  *
81  *  Descriptor Data
82  *
83  **************************************************************************/
84
85 // Descriptors are the data that your computer reads when it auto-detects
86 // this USB device (called "enumeration" in USB lingo).  The most commonly
87 // changed items are editable at the top of this file.  Changing things
88 // in here should only be done by those who've read chapter 9 of the USB
89 // spec and relevant portions of any USB class specifications!
90
91
92 static uint8_t const PROGMEM device_descriptor[] = {
93   18,                 // bLength
94   1,                  // bDescriptorType
95   0x00, 0x02,             // bcdUSB
96   0,                  // bDeviceClass
97   0,                  // bDeviceSubClass
98   0,                  // bDeviceProtocol
99   ENDPOINT0_SIZE,             // bMaxPacketSize0
100   LSB(VENDOR_ID), MSB(VENDOR_ID),     // idVendor
101   LSB(PRODUCT_ID), MSB(PRODUCT_ID),   // idProduct
102   0x00, 0x01,             // bcdDevice
103   1,                  // iManufacturer
104   2,                  // iProduct
105   0,                  // iSerialNumber
106   1                   // bNumConfigurations
107 };
108
109 // Keyboard Protocol 1, HID 1.11 spec, Appendix B, page 59-60
110 static uint8_t const PROGMEM keyboard_hid_report_desc[] = {
111   0x05, 0x01,          // Usage Page (Generic Desktop),
112   0x09, 0x06,          // Usage (Keyboard),
113   0xA1, 0x01,          // Collection (Application),
114   0x75, 0x01,          //   Report Size (1),
115   0x95, 0x08,          //   Report Count (8),
116   0x05, 0x07,          //   Usage Page (Key Codes),
117   0x19, 0xE0,          //   Usage Minimum (224),
118   0x29, 0xE7,          //   Usage Maximum (231),
119   0x15, 0x00,          //   Logical Minimum (0),
120   0x25, 0x01,          //   Logical Maximum (1),
121   0x81, 0x02,          //   Input (Data, Variable, Absolute), ;Modifier byte
122   0x95, 0x01,          //   Report Count (1),
123   0x75, 0x08,          //   Report Size (8),
124   0x81, 0x03,          //   Input (Constant),                 ;Reserved byte
125   0x95, 0x05,          //   Report Count (5),
126   0x75, 0x01,          //   Report Size (1),
127   0x05, 0x08,          //   Usage Page (LEDs),
128   0x19, 0x01,          //   Usage Minimum (1),
129   0x29, 0x05,          //   Usage Maximum (5),
130   0x91, 0x02,          //   Output (Data, Variable, Absolute), ;LED report
131   0x95, 0x01,          //   Report Count (1),
132   0x75, 0x03,          //   Report Size (3),
133   0x91, 0x03,          //   Output (Constant),                 ;LED report padding
134   0x95, 0x06,          //   Report Count (6),
135   0x75, 0x08,          //   Report Size (8),
136   0x15, 0x00,          //   Logical Minimum (0),
137   0x25, 0x68,          //   Logical Maximum(104),
138   0x05, 0x07,          //   Usage Page (Key Codes),
139   0x19, 0x00,          //   Usage Minimum (0),
140   0x29, 0x68,          //   Usage Maximum (104),
141   0x81, 0x00,          //   Input (Data, Array),
142   0xc0                 // End Collection
143 };
144
145 #define CONFIG1_DESC_SIZE        (9+9+9+7)
146 #define KEYBOARD_HID_DESC_OFFSET (9+9)
147 static uint8_t const PROGMEM config1_descriptor[CONFIG1_DESC_SIZE] = {
148   // configuration descriptor, USB spec 9.6.3, page 264-266, Table 9-10
149   9,                  // bLength;
150   2,                  // bDescriptorType;
151   LSB(CONFIG1_DESC_SIZE),         // wTotalLength
152   MSB(CONFIG1_DESC_SIZE),
153   1,                  // bNumInterfaces
154   1,                  // bConfigurationValue
155   0,                  // iConfiguration
156   0xC0,                   // bmAttributes
157   50,                 // bMaxPower
158   // interface descriptor, USB spec 9.6.5, page 267-269, Table 9-12
159   9,                  // bLength
160   4,                  // bDescriptorType
161   KEYBOARD_INTERFACE,         // bInterfaceNumber
162   0,                  // bAlternateSetting
163   1,                  // bNumEndpoints
164   0x03,                   // bInterfaceClass (0x03 = HID)
165   0x01,                   // bInterfaceSubClass (0x01 = Boot)
166   0x01,                   // bInterfaceProtocol (0x01 = Keyboard)
167   0,                  // iInterface
168   // HID interface descriptor, HID 1.11 spec, section 6.2.1
169   9,                  // bLength
170   0x21,                   // bDescriptorType
171   0x11, 0x01,             // bcdHID
172   0,                  // bCountryCode
173   1,                  // bNumDescriptors
174   0x22,                   // bDescriptorType
175   sizeof(keyboard_hid_report_desc),   // wDescriptorLength
176   0,
177   // endpoint descriptor, USB spec 9.6.6, page 269-271, Table 9-13
178   7,                  // bLength
179   5,                  // bDescriptorType
180   KEYBOARD_ENDPOINT | 0x80,       // bEndpointAddress
181   0x03,                   // bmAttributes (0x03=intr)
182   KEYBOARD_SIZE, 0,           // wMaxPacketSize
183   1                   // bInterval
184 };
185
186 // If you're desperate for a little extra code memory, these strings
187 // can be completely removed if iManufacturer, iProduct, iSerialNumber
188 // in the device desciptor are changed to zeros.
189 struct usb_string_descriptor_struct {
190   uint8_t bLength;
191   uint8_t bDescriptorType;
192   int16_t wString[];
193 };
194 static struct usb_string_descriptor_struct const PROGMEM string0 = {
195   4,
196   3,
197   {0x0409}
198 };
199 static struct usb_string_descriptor_struct const PROGMEM string1 = {
200   sizeof(STR_MANUFACTURER),
201   3,
202   STR_MANUFACTURER
203 };
204 static struct usb_string_descriptor_struct const PROGMEM string2 = {
205   sizeof(STR_PRODUCT),
206   3,
207   STR_PRODUCT
208 };
209
210 // This table defines which descriptor data is sent for each specific
211 // request from the host (in wValue and wIndex).
212 static struct descriptor_list_struct {
213   uint16_t    wValue;
214   uint16_t    wIndex;
215   const uint8_t   *addr;
216   uint8_t     length;
217 } const PROGMEM descriptor_list[] = {
218   {0x0100, 0x0000, device_descriptor, sizeof(device_descriptor)},
219   {0x0200, 0x0000, config1_descriptor, sizeof(config1_descriptor)},
220   {0x2200, KEYBOARD_INTERFACE, keyboard_hid_report_desc, sizeof(keyboard_hid_report_desc)},
221   {0x2100, KEYBOARD_INTERFACE, config1_descriptor+KEYBOARD_HID_DESC_OFFSET, 9},
222   {0x0300, 0x0000, (const uint8_t *)&string0, 4},
223   {0x0301, 0x0409, (const uint8_t *)&string1, sizeof(STR_MANUFACTURER)},
224   {0x0302, 0x0409, (const uint8_t *)&string2, sizeof(STR_PRODUCT)}
225 };
226 #define NUM_DESC_LIST (sizeof(descriptor_list)/sizeof(struct descriptor_list_struct))
227
228
229 /**************************************************************************
230  *
231  *  Variables - these are the only non-stack RAM usage
232  *
233  **************************************************************************/
234
235 // zero when we are not configured, non-zero when enumerated
236 static volatile uint8_t usb_configuration=0;
237
238 // which modifier keys are currently pressed
239 // 1=left ctrl,    2=left shift,   4=left alt,    8=left gui
240 // 16=right ctrl, 32=right shift, 64=right alt, 128=right gui
241 uint8_t keyboard_modifier_keys=0;
242
243 // which keys are currently pressed, up to 6 keys may be down at once
244 uint8_t keyboard_keys[6]={0,0,0,0,0,0};
245
246 // protocol setting from the host.  We use exactly the same report
247 // either way, so this variable only stores the setting since we
248 // are required to be able to report which setting is in use.
249 static uint8_t keyboard_protocol=1;
250
251 // the idle configuration, how often we send the report to the
252 // host (ms * 4) even when it hasn't changed
253 static uint8_t keyboard_idle_config=125;
254
255 // count until idle timeout
256 static uint8_t keyboard_idle_count=0;
257
258 // 1=num lock, 2=caps lock, 4=scroll lock, 8=compose, 16=kana
259 volatile uint8_t keyboard_leds=0;
260
261
262 /**************************************************************************
263  *
264  *  Public Functions - these are the API intended for the user
265  *
266  **************************************************************************/
267
268
269 // initialize USB
270 void usb_init(void)
271 {
272   HW_CONFIG();
273   USB_FREEZE();   // enable USB
274   PLL_CONFIG();               // config PLL
275   while (!(PLLCSR & (1<<PLOCK))) ;    // wait for PLL lock
276   USB_CONFIG();               // start USB clock
277   UDCON = 0;              // enable attach resistor
278   usb_configuration = 0;
279   UDIEN = (1<<EORSTE)|(1<<SOFE);
280   sei();
281 }
282
283 // return 0 if the USB is not configured, or the configuration
284 // number selected by the HOST
285 uint8_t usb_configured(void)
286 {
287   return usb_configuration;
288 }
289
290
291 // perform a single keystroke
292 int8_t usb_keyboard_press(uint8_t key, uint8_t modifier)
293 {
294   int8_t r;
295
296   keyboard_modifier_keys = modifier;
297   keyboard_keys[0] = key;
298   r = usb_keyboard_send();
299   if (r) return r;
300   keyboard_modifier_keys = 0;
301   keyboard_keys[0] = 0;
302   return usb_keyboard_send();
303 }
304
305 // send the contents of keyboard_keys and keyboard_modifier_keys
306 int8_t usb_keyboard_send(void)
307 {
308   uint8_t i, intr_state, timeout;
309
310   if (!usb_configuration) return -1;
311   intr_state = SREG;
312   cli();
313   UENUM = KEYBOARD_ENDPOINT;
314   timeout = UDFNUML + 50;
315   while (1) {
316     // are we ready to transmit?
317     if (UEINTX & (1<<RWAL)) break;
318     SREG = intr_state;
319     // has the USB gone offline?
320     if (!usb_configuration) return -1;
321     // have we waited too long?
322     if (UDFNUML == timeout) return -1;
323     // get ready to try checking again
324     intr_state = SREG;
325     cli();
326     UENUM = KEYBOARD_ENDPOINT;
327   }
328   UEDATX = keyboard_modifier_keys;
329   UEDATX = 0;
330   for (i=0; i<6; i++) {
331     UEDATX = keyboard_keys[i];
332   }
333   UEINTX = 0x3A;
334   keyboard_idle_count = 0;
335   SREG = intr_state;
336   return 0;
337 }
338
339 /**************************************************************************
340  *
341  *  Private Functions - not intended for general user consumption....
342  *
343  **************************************************************************/
344
345
346
347 // USB Device Interrupt - handle all device-level events
348 // the transmit buffer flushing is triggered by the start of frame
349 //
350 ISR(USB_GEN_vect)
351 {
352   uint8_t intbits, t, i;
353   static uint8_t div4=0;
354
355   intbits = UDINT;
356   UDINT = 0;
357   if (intbits & (1<<EORSTI)) {
358     UENUM = 0;
359     UECONX = 1;
360     UECFG0X = EP_TYPE_CONTROL;
361     UECFG1X = EP_SIZE(ENDPOINT0_SIZE) | EP_SINGLE_BUFFER;
362     UEIENX = (1<<RXSTPE);
363     usb_configuration = 0;
364   }
365   if ((intbits & (1<<SOFI)) && usb_configuration) {
366     if (keyboard_idle_config && (++div4 & 3) == 0) {
367       UENUM = KEYBOARD_ENDPOINT;
368       if (UEINTX & (1<<RWAL)) {
369         keyboard_idle_count++;
370         if (keyboard_idle_count == keyboard_idle_config) {
371           keyboard_idle_count = 0;
372           UEDATX = keyboard_modifier_keys;
373           UEDATX = 0;
374           for (i=0; i<6; i++) {
375             UEDATX = keyboard_keys[i];
376           }
377           UEINTX = 0x3A;
378         }
379       }
380     }
381   }
382 }
383
384
385
386 // Misc functions to wait for ready and send/receive packets
387 static inline void usb_wait_in_ready(void)
388 {
389   while (!(UEINTX & (1<<TXINI))) ;
390 }
391 static inline void usb_send_in(void)
392 {
393   UEINTX = ~(1<<TXINI);
394 }
395 static inline void usb_wait_receive_out(void)
396 {
397   while (!(UEINTX & (1<<RXOUTI))) ;
398 }
399 static inline void usb_ack_out(void)
400 {
401   UEINTX = ~(1<<RXOUTI);
402 }
403
404
405
406 // USB Endpoint Interrupt - endpoint 0 is handled here.  The
407 // other endpoints are manipulated by the user-callable
408 // functions, and the start-of-frame interrupt.
409 //
410 ISR(USB_COM_vect)
411 {
412   uint8_t intbits;
413   const uint8_t *list;
414   const uint8_t *cfg;
415   uint8_t i, n, len, en;
416   uint8_t bmRequestType;
417   uint8_t bRequest;
418   uint16_t wValue;
419   uint16_t wIndex;
420   uint16_t wLength;
421   uint16_t desc_val;
422   const uint8_t *desc_addr;
423   uint8_t desc_length;
424
425   UENUM = 0;
426   intbits = UEINTX;
427   if (intbits & (1<<RXSTPI)) {
428     bmRequestType = UEDATX;
429     bRequest = UEDATX;
430     wValue = UEDATX;
431     wValue |= (UEDATX << 8);
432     wIndex = UEDATX;
433     wIndex |= (UEDATX << 8);
434     wLength = UEDATX;
435     wLength |= (UEDATX << 8);
436     UEINTX = ~((1<<RXSTPI) | (1<<RXOUTI) | (1<<TXINI));
437     if (bRequest == GET_DESCRIPTOR) {
438       list = (const uint8_t *)descriptor_list;
439       for (i=0; ; i++) {
440         if (i >= NUM_DESC_LIST) {
441           UECONX = (1<<STALLRQ)|(1<<EPEN);  //stall
442           return;
443         }
444         desc_val = pgm_read_word(list);
445         if (desc_val != wValue) {
446           list += sizeof(struct descriptor_list_struct);
447           continue;
448         }
449         list += 2;
450         desc_val = pgm_read_word(list);
451         if (desc_val != wIndex) {
452           list += sizeof(struct descriptor_list_struct)-2;
453           continue;
454         }
455         list += 2;
456         desc_addr = (const uint8_t *)pgm_read_word(list);
457         list += 2;
458         desc_length = pgm_read_byte(list);
459         break;
460       }
461       len = (wLength < 256) ? wLength : 255;
462       if (len > desc_length) len = desc_length;
463       do {
464         // wait for host ready for IN packet
465         do {
466           i = UEINTX;
467         } while (!(i & ((1<<TXINI)|(1<<RXOUTI))));
468         if (i & (1<<RXOUTI)) return;    // abort
469         // send IN packet
470         n = len < ENDPOINT0_SIZE ? len : ENDPOINT0_SIZE;
471         for (i = n; i; i--) {
472           UEDATX = pgm_read_byte(desc_addr++);
473         }
474         len -= n;
475         usb_send_in();
476       } while (len || n == ENDPOINT0_SIZE);
477       return;
478     }
479     if (bRequest == SET_ADDRESS) {
480       usb_send_in();
481       usb_wait_in_ready();
482       UDADDR = wValue | (1<<ADDEN);
483       return;
484     }
485     if (bRequest == SET_CONFIGURATION && bmRequestType == 0) {
486       usb_configuration = wValue;
487       usb_send_in();
488       cfg = endpoint_config_table;
489       for (i=1; i<5; i++) {
490         UENUM = i;
491         en = pgm_read_byte(cfg++);
492         UECONX = en;
493         if (en) {
494           UECFG0X = pgm_read_byte(cfg++);
495           UECFG1X = pgm_read_byte(cfg++);
496         }
497       }
498       UERST = 0x1E;
499       UERST = 0;
500       return;
501     }
502     if (bRequest == GET_CONFIGURATION && bmRequestType == 0x80) {
503       usb_wait_in_ready();
504       UEDATX = usb_configuration;
505       usb_send_in();
506       return;
507     }
508
509     if (bRequest == GET_STATUS) {
510       usb_wait_in_ready();
511       i = 0;
512 #ifdef SUPPORT_ENDPOINT_HALT
513       if (bmRequestType == 0x82) {
514         UENUM = wIndex;
515         if (UECONX & (1<<STALLRQ)) i = 1;
516         UENUM = 0;
517       }
518 #endif
519       UEDATX = i;
520       UEDATX = 0;
521       usb_send_in();
522       return;
523     }
524 #ifdef SUPPORT_ENDPOINT_HALT
525     if ((bRequest == CLEAR_FEATURE || bRequest == SET_FEATURE)
526         && bmRequestType == 0x02 && wValue == 0) {
527       i = wIndex & 0x7F;
528       if (i >= 1 && i <= MAX_ENDPOINT) {
529         usb_send_in();
530         UENUM = i;
531         if (bRequest == SET_FEATURE) {
532           UECONX = (1<<STALLRQ)|(1<<EPEN);
533         } else {
534           UECONX = (1<<STALLRQC)|(1<<RSTDT)|(1<<EPEN);
535           UERST = (1 << i);
536           UERST = 0;
537         }
538         return;
539       }
540     }
541 #endif
542     if (wIndex == KEYBOARD_INTERFACE) {
543       if (bmRequestType == 0xA1) {
544         if (bRequest == HID_GET_REPORT) {
545           usb_wait_in_ready();
546           UEDATX = keyboard_modifier_keys;
547           UEDATX = 0;
548           for (i=0; i<6; i++) {
549             UEDATX = keyboard_keys[i];
550           }
551           usb_send_in();
552           return;
553         }
554         if (bRequest == HID_GET_IDLE) {
555           usb_wait_in_ready();
556           UEDATX = keyboard_idle_config;
557           usb_send_in();
558           return;
559         }
560         if (bRequest == HID_GET_PROTOCOL) {
561           usb_wait_in_ready();
562           UEDATX = keyboard_protocol;
563           usb_send_in();
564           return;
565         }
566       }
567       if (bmRequestType == 0x21) {
568         if (bRequest == HID_SET_REPORT) {
569           usb_wait_receive_out();
570           keyboard_leds = UEDATX;
571           usb_ack_out();
572           usb_send_in();
573           return;
574         }
575         if (bRequest == HID_SET_IDLE) {
576           keyboard_idle_config = (wValue >> 8);
577           keyboard_idle_count = 0;
578           usb_send_in();
579           return;
580         }
581         if (bRequest == HID_SET_PROTOCOL) {
582           keyboard_protocol = wValue;
583           usb_send_in();
584           return;
585         }
586       }
587     }
588   }
589   UECONX = (1<<STALLRQ) | (1<<EPEN);  // stall
590 }