1 /* USB Keyboard and CDC Serial Device for Teensy USB Development Board
2 * Copyright (c) 2009 PJRC.COM, LLC
3 * Modifications by Jacob Alexander (2011-2014)
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:
12 * The above copyright notice and this permission notice shall be included in
13 * all copies or substantial portions of the Software.
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
26 #include "usb_keyboard_serial.h"
29 // ----- Variables -----
31 // zero when we are not configured, non-zero when enumerated
32 static volatile uint8_t usb_configuration = 0;
34 // the time remaining before we transmit any partially full
35 // packet, or send a zero length packet.
36 static volatile uint8_t transmit_flush_timer = 0;
37 static uint8_t transmit_previous_timeout = 0;
39 // serial port settings (baud rate, control signals, etc) set
40 // by the PC. These are ignored, but kept in RAM.
41 static uint8_t cdc_line_coding[7] = {0x00, 0xE1, 0x00, 0x00, 0x00, 0x00, 0x08};
42 static uint8_t cdc_line_rtsdtr = 0;
46 // ----- USB Keyboard Functions -----
48 // Sends normal keyboard out to host
49 // NOTE: Make sure to match the descriptor
50 void usb_keyboard_toHost()
55 UEDATX = USBKeys_Modifiers;
58 for ( i = 0; i < 6; i++)
60 UEDATX = USBKeys_Array[i];
65 // Sends NKRO keyboard out to host
66 // NOTE: Make sure to match the descriptor
67 void usb_nkrokeyboard_toHost()
74 UEDATX = USBKeys_Modifiers;
85 for ( i = 0; i < 6; i++)
87 UEDATX = USBKeys_Array[i];
92 // send the contents of USBKeys_Array and USBKeys_Modifiers
93 int8_t usb_keyboard_send()
95 uint8_t intr_state, timeout;
98 timeout = UDFNUML + 50;
100 // Ready to transmit keypresses?
105 // has the USB gone offline? or exceeded timeout?
106 if ( !usb_configuration || UDFNUML == timeout )
109 // get ready to try checking again
113 // If not using Boot protocol, send NKRO
114 UENUM = USBKeys_Protocol ? KEYBOARD_NKRO_ENDPOINT : KEYBOARD_ENDPOINT;
115 } while ( !( UEINTX & (1 << RWAL) ) );
117 // Send normal keyboard interrupt packet(s)
118 switch ( USBKeys_Protocol )
121 usb_keyboard_toHost();
123 USBKeys_Idle_Count = 0;
130 // ----- USB Virtual Serial Port (CDC) Functions -----
132 // get the next character, or -1 if nothing received
133 int16_t usb_serial_getchar(void)
135 uint8_t c, intr_state;
137 // interrupts are disabled so these functions can be
138 // used from the main program or interrupt context,
139 // even both in the same program!
142 if (!usb_configuration) {
146 UENUM = CDC_RX_ENDPOINT;
149 if (!(c & (1<<RWAL))) {
151 if (c & (1<<RXOUTI)) {
158 // take one byte out of the buffer
160 // if buffer completely used, release it
161 if (!(UEINTX & (1<<RWAL))) UEINTX = 0x6B;
166 // number of bytes available in the receive buffer
167 uint8_t usb_serial_available(void)
169 uint8_t n=0, i, intr_state;
173 if (usb_configuration) {
174 UENUM = CDC_RX_ENDPOINT;
178 if (i & (1<<RXOUTI) && !(i & (1<<RWAL))) UEINTX = 0x6B;
185 // discard any buffered input
186 void usb_serial_flush_input(void)
190 if (usb_configuration) {
193 UENUM = CDC_RX_ENDPOINT;
194 while ((UEINTX & (1<<RWAL))) {
201 // transmit a character. 0 returned on success, -1 on error
202 int8_t usb_serial_putchar(uint8_t c)
204 uint8_t timeout, intr_state;
206 // if we're not online (enumerated and configured), error
207 if (!usb_configuration) return -1;
208 // interrupts are disabled so these functions can be
209 // used from the main program or interrupt context,
210 // even both in the same program!
213 UENUM = CDC_TX_ENDPOINT;
214 // if we gave up due to timeout before, don't wait again
215 if (transmit_previous_timeout) {
216 if (!(UEINTX & (1<<RWAL))) {
220 transmit_previous_timeout = 0;
222 // wait for the FIFO to be ready to accept data
223 timeout = UDFNUML + TRANSMIT_TIMEOUT;
225 // are we ready to transmit?
226 if (UEINTX & (1<<RWAL)) break;
228 // have we waited too long? This happens if the user
229 // is not running an application that is listening
230 if (UDFNUML == timeout) {
231 transmit_previous_timeout = 1;
234 // has the USB gone offline?
235 if (!usb_configuration) return -1;
236 // get ready to try checking again
239 UENUM = CDC_TX_ENDPOINT;
241 // actually write the byte into the FIFO
243 // if this completed a packet, transmit it now!
244 if (!(UEINTX & (1<<RWAL))) UEINTX = 0x3A;
245 transmit_flush_timer = TRANSMIT_FLUSH_TIMEOUT;
251 // transmit a character, but do not wait if the buffer is full,
252 // 0 returned on success, -1 on buffer full or error
253 int8_t usb_serial_putchar_nowait(uint8_t c)
257 if (!usb_configuration) return -1;
260 UENUM = CDC_TX_ENDPOINT;
261 if (!(UEINTX & (1<<RWAL))) {
266 // actually write the byte into the FIFO
268 // if this completed a packet, transmit it now!
269 if (!(UEINTX & (1<<RWAL))) UEINTX = 0x3A;
270 transmit_flush_timer = TRANSMIT_FLUSH_TIMEOUT;
275 // transmit a buffer.
276 // 0 returned on success, -1 on error
277 // This function is optimized for speed! Each call takes approx 6.1 us overhead
278 // plus 0.25 us per byte. 12 Mbit/sec USB has 8.67 us per-packet overhead and
279 // takes 0.67 us per byte. If called with 64 byte packet-size blocks, this function
280 // can transmit at full USB speed using 43% CPU time. The maximum theoretical speed
281 // is 19 packets per USB frame, or 1216 kbytes/sec. However, bulk endpoints have the
282 // lowest priority, so any other USB devices will likely reduce the speed. Speed
283 // can also be limited by how quickly the PC-based software reads data, as the host
284 // controller in the PC will not allocate bandwitdh without a pending read request.
285 // (thanks to Victor Suarez for testing and feedback and initial code)
287 int8_t usb_serial_write(const char *buffer, uint16_t size)
289 uint8_t timeout, intr_state, write_size;
291 // if we're not online (enumerated and configured), error
292 if (!usb_configuration) return -1;
293 // interrupts are disabled so these functions can be
294 // used from the main program or interrupt context,
295 // even both in the same program!
298 UENUM = CDC_TX_ENDPOINT;
299 // if we gave up due to timeout before, don't wait again
301 if (transmit_previous_timeout) {
302 if (!(UEINTX & (1<<RWAL))) {
306 transmit_previous_timeout = 0;
309 // each iteration of this loop transmits a packet
311 // wait for the FIFO to be ready to accept data
312 timeout = UDFNUML + TRANSMIT_TIMEOUT;
314 // are we ready to transmit?
315 if (UEINTX & (1<<RWAL)) break;
317 // have we waited too long? This happens if the user
318 // is not running an application that is listening
319 if (UDFNUML == timeout) {
320 transmit_previous_timeout = 1;
323 // has the USB gone offline?
324 if (!usb_configuration) return -4;
325 // get ready to try checking again
328 UENUM = CDC_TX_ENDPOINT;
331 // compute how many bytes will fit into the next packet
332 write_size = CDC_TX_SIZE - UEBCLX;
333 if (write_size > size) write_size = size;
337 switch (write_size) {
338 #if (CDC_TX_SIZE == 64)
339 case 64: UEDATX = *buffer++;
340 case 63: UEDATX = *buffer++;
341 case 62: UEDATX = *buffer++;
342 case 61: UEDATX = *buffer++;
343 case 60: UEDATX = *buffer++;
344 case 59: UEDATX = *buffer++;
345 case 58: UEDATX = *buffer++;
346 case 57: UEDATX = *buffer++;
347 case 56: UEDATX = *buffer++;
348 case 55: UEDATX = *buffer++;
349 case 54: UEDATX = *buffer++;
350 case 53: UEDATX = *buffer++;
351 case 52: UEDATX = *buffer++;
352 case 51: UEDATX = *buffer++;
353 case 50: UEDATX = *buffer++;
354 case 49: UEDATX = *buffer++;
355 case 48: UEDATX = *buffer++;
356 case 47: UEDATX = *buffer++;
357 case 46: UEDATX = *buffer++;
358 case 45: UEDATX = *buffer++;
359 case 44: UEDATX = *buffer++;
360 case 43: UEDATX = *buffer++;
361 case 42: UEDATX = *buffer++;
362 case 41: UEDATX = *buffer++;
363 case 40: UEDATX = *buffer++;
364 case 39: UEDATX = *buffer++;
365 case 38: UEDATX = *buffer++;
366 case 37: UEDATX = *buffer++;
367 case 36: UEDATX = *buffer++;
368 case 35: UEDATX = *buffer++;
369 case 34: UEDATX = *buffer++;
370 case 33: UEDATX = *buffer++;
372 #if (CDC_TX_SIZE >= 32)
373 case 32: UEDATX = *buffer++;
374 case 31: UEDATX = *buffer++;
375 case 30: UEDATX = *buffer++;
376 case 29: UEDATX = *buffer++;
377 case 28: UEDATX = *buffer++;
378 case 27: UEDATX = *buffer++;
379 case 26: UEDATX = *buffer++;
380 case 25: UEDATX = *buffer++;
381 case 24: UEDATX = *buffer++;
382 case 23: UEDATX = *buffer++;
383 case 22: UEDATX = *buffer++;
384 case 21: UEDATX = *buffer++;
385 case 20: UEDATX = *buffer++;
386 case 19: UEDATX = *buffer++;
387 case 18: UEDATX = *buffer++;
388 case 17: UEDATX = *buffer++;
390 #if (CDC_TX_SIZE >= 16)
391 case 16: UEDATX = *buffer++;
392 case 15: UEDATX = *buffer++;
393 case 14: UEDATX = *buffer++;
394 case 13: UEDATX = *buffer++;
395 case 12: UEDATX = *buffer++;
396 case 11: UEDATX = *buffer++;
397 case 10: UEDATX = *buffer++;
398 case 9: UEDATX = *buffer++;
400 case 8: UEDATX = *buffer++;
401 case 7: UEDATX = *buffer++;
402 case 6: UEDATX = *buffer++;
403 case 5: UEDATX = *buffer++;
404 case 4: UEDATX = *buffer++;
405 case 3: UEDATX = *buffer++;
406 case 2: UEDATX = *buffer++;
408 case 1: UEDATX = *buffer++;
411 // if this completed a packet, transmit it now!
412 if (!(UEINTX & (1<<RWAL))) UEINTX = 0x3A;
413 transmit_flush_timer = TRANSMIT_FLUSH_TIMEOUT;
419 // immediately transmit any buffered output.
420 // This doesn't actually transmit the data - that is impossible!
421 // USB devices only transmit when the host allows, so the best
422 // we can do is release the FIFO buffer for when the host wants it
423 void usb_serial_flush_output(void)
429 if (transmit_flush_timer) {
430 UENUM = CDC_TX_ENDPOINT;
432 transmit_flush_timer = 0;
437 // functions to read the various async serial settings. These
438 // aren't actually used by USB at all (communication is always
439 // at full USB speed), but they are set by the host so we can
440 // set them properly if we're converting the USB to a real serial
442 uint32_t usb_serial_get_baud(void)
444 uint32_t *baud = (uint32_t*)cdc_line_coding;
447 uint8_t usb_serial_get_stopbits(void)
449 return cdc_line_coding[4];
451 uint8_t usb_serial_get_paritytype(void)
453 return cdc_line_coding[5];
455 uint8_t usb_serial_get_numbits(void)
457 return cdc_line_coding[6];
459 uint8_t usb_serial_get_control(void)
461 return cdc_line_rtsdtr;
464 // write the control signals, DCD, DSR, RI, etc
465 // There is no CTS signal. If software on the host has transmitted
466 // data to you but you haven't been calling the getchar function,
467 // it remains buffered (either here or on the host) and can not be
468 // lost because you weren't listening at the right time, like it
469 // would in real serial communication.
470 int8_t usb_serial_set_control(uint8_t signals)
476 if (!usb_configuration) {
477 // we're not enumerated/configured
482 UENUM = CDC_ACM_ENDPOINT;
483 if (!(UEINTX & (1<<RWAL))) {
485 // TODO; should this try to abort the previously
486 // buffered message??
494 UEDATX = 0; // 0 seems to work nicely. what if this is 1??
506 // ----- General USB Functions -----
508 // Set the avr into firmware reload mode
509 void usb_device_reload()
512 // Disable watchdog, if enabled
513 // Disable all peripherals
516 USBCON = (1 << FRZCLK); // Disable USB
520 #if defined(__AVR_AT90USB162__) // Teensy 1.0
521 EIMSK = 0; PCICR = 0; SPCR = 0; ACSR = 0; EECR = 0;
522 TIMSK0 = 0; TIMSK1 = 0; UCSR1B = 0;
523 DDRB = 0; DDRC = 0; DDRD = 0;
524 PORTB = 0; PORTC = 0; PORTD = 0;
525 asm volatile("jmp 0x3E00");
526 #elif defined(__AVR_ATmega32U4__) // Teensy 2.0
527 EIMSK = 0; PCICR = 0; SPCR = 0; ACSR = 0; EECR = 0; ADCSRA = 0;
528 TIMSK0 = 0; TIMSK1 = 0; TIMSK3 = 0; TIMSK4 = 0; UCSR1B = 0; TWCR = 0;
529 DDRB = 0; DDRC = 0; DDRD = 0; DDRE = 0; DDRF = 0; TWCR = 0;
530 PORTB = 0; PORTC = 0; PORTD = 0; PORTE = 0; PORTF = 0;
531 asm volatile("jmp 0x7E00");
532 #elif defined(__AVR_AT90USB646__) // Teensy++ 1.0
533 EIMSK = 0; PCICR = 0; SPCR = 0; ACSR = 0; EECR = 0; ADCSRA = 0;
534 TIMSK0 = 0; TIMSK1 = 0; TIMSK2 = 0; TIMSK3 = 0; UCSR1B = 0; TWCR = 0;
535 DDRA = 0; DDRB = 0; DDRC = 0; DDRD = 0; DDRE = 0; DDRF = 0;
536 PORTA = 0; PORTB = 0; PORTC = 0; PORTD = 0; PORTE = 0; PORTF = 0;
537 asm volatile("jmp 0xFC00");
538 #elif defined(__AVR_AT90USB1286__) // Teensy++ 2.0
539 EIMSK = 0; PCICR = 0; SPCR = 0; ACSR = 0; EECR = 0; ADCSRA = 0;
540 TIMSK0 = 0; TIMSK1 = 0; TIMSK2 = 0; TIMSK3 = 0; UCSR1B = 0; TWCR = 0;
541 DDRA = 0; DDRB = 0; DDRC = 0; DDRD = 0; DDRE = 0; DDRF = 0;
542 PORTA = 0; PORTB = 0; PORTC = 0; PORTD = 0; PORTE = 0; PORTF = 0;
543 asm volatile("jmp 0x1FC00");
548 // WDT Setup for software reset the chip
560 USB_FREEZE(); // enable USB
561 PLL_CONFIG(); // config PLL
562 while (!(PLLCSR & (1<<PLOCK))) ; // wait for PLL lock
563 USB_CONFIG(); // start USB clock
564 UDCON = 0; // enable attach resistor
565 usb_configuration = 0;
566 UDIEN = (1<<EORSTE) | (1<<SOFE);
569 // Disable watchdog timer after possible software reset
570 //wdt_init(); // XXX Not working...seems to be ok without this, not sure though
573 // return 0 if the USB is not configured, or the configuration
574 // number selected by the HOST
575 uint8_t usb_configured()
577 return usb_configuration;
580 // USB Device Interrupt - handle all device-level events
581 // the transmit buffer flushing is triggered by the start of frame
585 uint8_t intbits, t_cdc;
589 if ( intbits & (1 << EORSTI) )
593 UECFG0X = EP_TYPE_CONTROL;
594 UECFG1X = EP_SIZE(ENDPOINT0_SIZE) | EP_SINGLE_BUFFER;
595 UEIENX = (1 << RXSTPE);
596 usb_configuration = 0;
599 if ( (intbits & (1 << SOFI)) && usb_configuration )
601 t_cdc = transmit_flush_timer;
604 transmit_flush_timer = --t_cdc;
607 UENUM = CDC_TX_ENDPOINT;
611 static uint8_t div4 = 0;
612 if ( USBKeys_Idle_Config && (++div4 & 3) == 0 )
614 USBKeys_Idle_Count++;
615 if ( USBKeys_Idle_Count == USBKeys_Idle_Config )
617 // XXX TODO Is this even used? If so, when? -Jacob
618 // From hasu's code, this section looks like it could fix the Mac SET_IDLE problem
619 // Send normal keyboard interrupt packet(s)
620 //usb_keyboard_toHost();
628 // Misc functions to wait for ready and send/receive packets
629 static inline void usb_wait_in_ready(void)
631 while (!(UEINTX & (1<<TXINI))) ;
633 static inline void usb_send_in(void)
635 UEINTX = ~(1<<TXINI);
637 static inline void usb_wait_receive_out(void)
639 while (!(UEINTX & (1<<RXOUTI))) ;
641 static inline void usb_ack_out(void)
643 UEINTX = ~(1<<RXOUTI);
648 // USB Endpoint Interrupt - endpoint 0 is handled here. The
649 // other endpoints are manipulated by the user-callable
650 // functions, and the start-of-frame interrupt.
657 uint8_t i, n, len, en;
659 uint8_t bmRequestType;
665 const uint8_t *desc_addr;
670 if (intbits & (1<<RXSTPI)) {
671 bmRequestType = UEDATX;
674 wValue |= (UEDATX << 8);
676 wIndex |= (UEDATX << 8);
678 wLength |= (UEDATX << 8);
679 UEINTX = ~((1<<RXSTPI) | (1<<RXOUTI) | (1<<TXINI));
681 if ( bRequest == GET_DESCRIPTOR )
683 list = (const uint8_t *)descriptor_list;
686 if ( i >= NUM_DESC_LIST )
688 UECONX = (1 << STALLRQ) | (1 << EPEN); //stall
691 desc_val = pgm_read_word(list);
692 if ( desc_val != wValue )
694 list += sizeof( struct descriptor_list_struct );
698 desc_val = pgm_read_word(list);
699 if ( desc_val != wIndex )
701 list += sizeof(struct descriptor_list_struct) - 2;
705 desc_addr = (const uint8_t *)pgm_read_word(list);
707 desc_length = pgm_read_byte(list);
710 len = (wLength < 256) ? wLength : 255;
711 if (len > desc_length) len = desc_length;
713 // wait for host ready for IN packet
716 } while (!(i & ((1<<TXINI)|(1<<RXOUTI))));
717 if (i & (1<<RXOUTI)) return; // abort
719 n = len < ENDPOINT0_SIZE ? len : ENDPOINT0_SIZE;
720 for (i = n; i; i--) {
721 UEDATX = pgm_read_byte(desc_addr++);
725 } while (len || n == ENDPOINT0_SIZE);
729 if (bRequest == SET_ADDRESS) {
732 UDADDR = wValue | (1<<ADDEN);
736 if ( bRequest == SET_CONFIGURATION && bmRequestType == 0 )
738 usb_configuration = wValue;
740 transmit_flush_timer = 0;
742 cfg = endpoint_config_table;
743 // Setup each of the 6 additional endpoints (0th already configured)
744 for ( i = 1; i < 6; i++ )
747 en = pgm_read_byte(cfg++);
751 UECFG0X = pgm_read_byte(cfg++);
752 UECFG1X = pgm_read_byte(cfg++);
760 if (bRequest == GET_CONFIGURATION && bmRequestType == 0x80) {
762 UEDATX = usb_configuration;
767 //if ( wIndex == KEYBOARD_INTERFACE )
768 if ( wIndex == KEYBOARD_INTERFACE || wIndex == KEYBOARD_NKRO_INTERFACE )
770 if ( bmRequestType == 0xA1)
772 if ( bRequest == HID_GET_REPORT )
776 // XXX TODO Is this even used? If so, when? -Jacob
777 // Send normal keyboard interrupt packet(s)
778 //usb_keyboard_toHost();
783 if ( bRequest == HID_GET_IDLE )
786 UEDATX = USBKeys_Idle_Config;
790 if ( bRequest == HID_GET_PROTOCOL )
793 UEDATX = USBKeys_Protocol;
797 USBKeys_Protocol = bRequest;
799 if ( bmRequestType == 0x21 )
801 if ( bRequest == HID_SET_REPORT )
803 usb_wait_receive_out();
804 USBKeys_LEDs = UEDATX;
809 if ( bRequest == HID_SET_IDLE )
811 USBKeys_Idle_Config = (wValue >> 8);
812 USBKeys_Idle_Count = 0;
813 //usb_wait_in_ready();
817 if ( bRequest == HID_SET_PROTOCOL )
819 USBKeys_Protocol = wValue; // 0 - Boot Mode, 1 - NKRO Mode
820 //usb_wait_in_ready();
827 if (bRequest == CDC_GET_LINE_CODING && bmRequestType == 0xA1) {
830 for (i=0; i<7; i++) {
837 if (bRequest == CDC_SET_LINE_CODING && bmRequestType == 0x21) {
838 usb_wait_receive_out();
840 for (i=0; i<7; i++) {
848 if (bRequest == CDC_SET_CONTROL_LINE_STATE && bmRequestType == 0x21) {
849 cdc_line_rtsdtr = wValue;
855 if (bRequest == GET_STATUS) {
858 if (bmRequestType == 0x82) {
860 if (UECONX & (1<<STALLRQ)) i = 1;
869 if ((bRequest == CLEAR_FEATURE || bRequest == SET_FEATURE)
870 && bmRequestType == 0x02 && wValue == 0) {
872 if (i >= 1 && i <= MAX_ENDPOINT) {
875 if (bRequest == SET_FEATURE) {
876 UECONX = (1<<STALLRQ)|(1<<EPEN);
878 UECONX = (1<<STALLRQC)|(1<<RSTDT)|(1<<EPEN);
886 UECONX = (1 << STALLRQ) | (1 << EPEN); // stall