3      Copyright (C) Dean Camera, 2009. 
   5   dean [at] fourwalledcubicle [dot] com 
   6       www.fourwalledcubicle.com 
  10   Copyright 2009  Denver Gingerich (denver [at] ossguy [dot] com) 
  11       Based on code by Dean Camera (dean [at] fourwalledcubicle [dot] com) 
  13   Permission to use, copy, modify, and distribute this software 
  14   and its documentation for any purpose and without fee is hereby 
  15   granted, provided that the above copyright notice appear in all 
  16   copies and that both that the copyright notice and this 
  17   permission notice and warranty disclaimer appear in supporting 
  18   documentation, and that the name of the author not be used in 
  19   advertising or publicity pertaining to distribution of the 
  20   software without specific, written prior permission. 
  22   The author disclaim all warranties with regard to this 
  23   software, including all implied warranties of merchantability 
  24   and fitness.  In no event shall the author be liable for any 
  25   special, indirect or consequential damages or any damages 
  26   whatsoever resulting from loss of use, data or profits, whether 
  27   in an action of contract, negligence or other tortious action, 
  28   arising out of or in connection with the use or performance of 
  34  *  Main source file for the Keyboard demo. This file contains the main tasks of the demo and 
  35  *  is responsible for the initial application hardware configuration. 
  40 /* Scheduler Task List */ 
  43         #if !defined(INTERRUPT_CONTROL_ENDPOINT) 
  44         { .Task 
= USB_USBTask          
, .TaskStatus 
= TASK_STOP 
}, 
  47         #if !defined(INTERRUPT_DATA_ENDPOINT) 
  48         { .Task 
= USB_Keyboard_Report  
, .TaskStatus 
= TASK_STOP 
}, 
  52 /* Global Variables */ 
  53 /** Indicates what report mode the host has requested, true for normal HID reporting mode, false for special boot 
  54  *  protocol reporting mode. 
  56 bool UsingReportProtocol 
= true; 
  58 /** Current Idle period. This is set by the host via a Set Idle HID class request to silence the device's reports 
  59  *  for either the entire idle duration, or until the report status changes (e.g. the user moves the mouse). 
  61 uint8_t IdleCount 
= 0; 
  63 /** Current Idle period remaining. When the IdleCount value is set, this tracks the remaining number of idle 
  64  *  milliseconds. This is separate to the IdleCount timer and is incremented and compared as the host may request  
  65  *  the current idle period via a Get Idle HID class request, thus its value must be preserved. 
  67 uint16_t IdleMSRemaining 
= 0; 
  70 /** Main program entry point. This routine configures the hardware required by the application, then 
  71  *  starts the scheduler to run the USB management task. 
  75         /* Disable watchdog if enabled by bootloader/fuses */ 
  76         MCUSR 
&= ~(1 << WDRF
); 
  79         /* Disable clock division */ 
  80         clock_prescale_set(clock_div_1
); 
  82         /* Hardware Initialization */ 
  86         /* Millisecond timer initialization, with output compare interrupt enabled for the idle timing */ 
  88         TCCR0A 
= (1 << WGM01
); 
  89         TCCR0B 
= ((1 << CS01
) | (1 << CS00
)); 
  90         TIMSK0 
= (1 << OCIE0A
); 
  92         /* Indicate USB not ready */ 
  93         UpdateStatus(Status_USBNotReady
); 
  95         /* Initialize Scheduler so that it can be used */ 
  98         /* Initialize USB Subsystem */ 
 101         /* Scheduling - routine never returns, so put this last in the main function */ 
 105 /** Event handler for the USB_Connect event. This indicates that the device is enumerating via the status LEDs and 
 106  *  starts the library USB task to begin the enumeration and USB management process. 
 108 EVENT_HANDLER(USB_Connect
) 
 110         #if !defined(INTERRUPT_CONTROL_ENDPOINT) 
 111         /* Start USB management task */ 
 112         Scheduler_SetTaskMode(USB_USBTask
, TASK_RUN
); 
 115         /* Indicate USB enumerating */ 
 116         UpdateStatus(Status_USBEnumerating
); 
 118         /* Default to report protocol on connect */ 
 119         UsingReportProtocol 
= true; 
 122 /** Event handler for the USB_Reset event. This fires when the USB interface is reset by the USB host, before the 
 123  *  enumeration process begins, and enables the control endpoint interrupt so that control requests can be handled 
 124  *  asynchronously when they arrive rather than when the control endpoint is polled manually. 
 126 EVENT_HANDLER(USB_Reset
) 
 128         #if defined(INTERRUPT_CONTROL_ENDPOINT) 
 129         /* Select the control endpoint */ 
 130         Endpoint_SelectEndpoint(ENDPOINT_CONTROLEP
); 
 132         /* Enable the endpoint SETUP interrupt ISR for the control endpoint */ 
 133         USB_INT_Enable(ENDPOINT_INT_SETUP
); 
 137 /** Event handler for the USB_Disconnect event. This indicates that the device is no longer connected to a host via 
 140 EVENT_HANDLER(USB_Disconnect
) 
 142         /* Stop running keyboard reporting and USB management tasks */ 
 143         #if !defined(INTERRUPT_DATA_ENDPOINT) 
 144         Scheduler_SetTaskMode(USB_Keyboard_Report
, TASK_STOP
); 
 147         #if !defined(INTERRUPT_CONTROL_ENDPOINT) 
 148         Scheduler_SetTaskMode(USB_USBTask
, TASK_STOP
); 
 151         /* Indicate USB not ready */ 
 152         UpdateStatus(Status_USBNotReady
); 
 155 /** Event handler for the USB_ConfigurationChanged event. This is fired when the host sets the current configuration 
 156  *  of the USB device after enumeration, and configures the keyboard device endpoints. 
 158 EVENT_HANDLER(USB_ConfigurationChanged
) 
 160         /* Setup Keyboard Keycode Report Endpoint */ 
 161         Endpoint_ConfigureEndpoint(KEYBOARD_EPNUM
, EP_TYPE_INTERRUPT
, 
 162                                        ENDPOINT_DIR_IN
, KEYBOARD_EPSIZE
, 
 163                                    ENDPOINT_BANK_SINGLE
); 
 165         #if defined(INTERRUPT_DATA_ENDPOINT) 
 166         /* Enable the endpoint IN interrupt ISR for the report endpoint */ 
 167         USB_INT_Enable(ENDPOINT_INT_IN
); 
 170         /* Setup Keyboard LED Report Endpoint */ 
 171         Endpoint_ConfigureEndpoint(KEYBOARD_LEDS_EPNUM
, EP_TYPE_INTERRUPT
, 
 172                                        ENDPOINT_DIR_OUT
, KEYBOARD_EPSIZE
, 
 173                                    ENDPOINT_BANK_SINGLE
); 
 175         #if defined(INTERRUPT_DATA_ENDPOINT) 
 176         /* Enable the endpoint OUT interrupt ISR for the LED report endpoint */ 
 177         USB_INT_Enable(ENDPOINT_INT_OUT
); 
 180         /* Indicate USB connected and ready */ 
 181         UpdateStatus(Status_USBReady
); 
 183         #if !defined(INTERRUPT_DATA_ENDPOINT) 
 184         /* Start running keyboard reporting task */ 
 185         Scheduler_SetTaskMode(USB_Keyboard_Report
, TASK_RUN
); 
 189 /** Event handler for the USB_UnhandledControlPacket event. This is used to catch standard and class specific 
 190  *  control requests that are not handled internally by the USB library (including the HID commands, which are 
 191  *  all issued via the control endpoint), so that they can be handled appropriately for the application. 
 193 EVENT_HANDLER(USB_UnhandledControlPacket
) 
 195         /* Handle HID Class specific requests */ 
 196         switch (USB_ControlRequest
.bRequest
) 
 199                         if (USB_ControlRequest
.bmRequestType 
== (REQDIR_DEVICETOHOST 
| REQTYPE_CLASS 
| REQREC_INTERFACE
)) 
 201                                 USB_KeyboardReport_Data_t KeyboardReportData
; 
 203                                 Endpoint_ClearSETUP(); 
 205                                 /* Create the next keyboard report for transmission to the host */ 
 206                                 CreateKeyboardReport(&KeyboardReportData
); 
 208                                 /* Write the report data to the control endpoint */ 
 209                                 Endpoint_Write_Control_Stream_LE(&KeyboardReportData
, sizeof(KeyboardReportData
)); 
 211                                 /* Finalize the stream transfer to send the last packet or clear the host abort */ 
 217                         if (USB_ControlRequest
.bmRequestType 
== (REQDIR_HOSTTODEVICE 
| REQTYPE_CLASS 
| REQREC_INTERFACE
)) 
 219                                 Endpoint_ClearSETUP(); 
 221                                 /* Wait until the LED report has been sent by the host */ 
 222                                 while (!(Endpoint_IsOUTReceived())); 
 224                                 /* Read in the LED report from the host */ 
 225                                 uint8_t LEDStatus 
= Endpoint_Read_Byte(); 
 227                                 /* Process the incoming LED report */ 
 228                                 ProcessLEDReport(LEDStatus
); 
 230                                 /* Clear the endpoint data */ 
 233                                 /* Acknowledge status stage */ 
 234                                 while (!(Endpoint_IsINReady())); 
 239                 case REQ_GetProtocol
: 
 240                         if (USB_ControlRequest
.bmRequestType 
== (REQDIR_DEVICETOHOST 
| REQTYPE_CLASS 
| REQREC_INTERFACE
)) 
 242                                 Endpoint_ClearSETUP(); 
 244                                 /* Write the current protocol flag to the host */ 
 245                                 Endpoint_Write_Byte(UsingReportProtocol
); 
 247                                 /* Send the flag to the host */ 
 250                                 /* Acknowledge status stage */ 
 251                                 while (!(Endpoint_IsOUTReceived())); 
 256                 case REQ_SetProtocol
: 
 257                         if (USB_ControlRequest
.bmRequestType 
== (REQDIR_HOSTTODEVICE 
| REQTYPE_CLASS 
| REQREC_INTERFACE
)) 
 259                                 Endpoint_ClearSETUP(); 
 261                                 /* Set or clear the flag depending on what the host indicates that the current Protocol should be */ 
 262                                 UsingReportProtocol 
= (USB_ControlRequest
.wValue 
!= 0x0000); 
 264                                 /* Acknowledge status stage */ 
 265                                 while (!(Endpoint_IsINReady())); 
 271                         if (USB_ControlRequest
.bmRequestType 
== (REQDIR_HOSTTODEVICE 
| REQTYPE_CLASS 
| REQREC_INTERFACE
)) 
 273                                 Endpoint_ClearSETUP(); 
 275                                 /* Get idle period in MSB */ 
 276                                 IdleCount 
= (USB_ControlRequest
.wValue 
>> 8); 
 278                                 /* Acknowledge status stage */ 
 279                                 while (!(Endpoint_IsINReady())); 
 285                         if (USB_ControlRequest
.bmRequestType 
== (REQDIR_DEVICETOHOST 
| REQTYPE_CLASS 
| REQREC_INTERFACE
)) 
 287                                 Endpoint_ClearSETUP(); 
 289                                 /* Write the current idle duration to the host */ 
 290                                 Endpoint_Write_Byte(IdleCount
); 
 292                                 /* Send the flag to the host */ 
 295                                 /* Acknowledge status stage */ 
 296                                 while (!(Endpoint_IsOUTReceived())); 
 304 /** ISR for the timer 0 compare vector. This ISR fires once each millisecond, and increments the 
 305  *  scheduler elapsed idle period counter when the host has set an idle period. 
 307 ISR(TIMER0_COMPA_vect
, ISR_BLOCK
) 
 309         /* One millisecond has elapsed, decrement the idle time remaining counter if it has not already elapsed */ 
 314 /** Fills the given HID report data structure with the next HID report to send to the host. 
 316  *  \param ReportData  Pointer to a HID report data structure to be filled 
 318 void CreateKeyboardReport(USB_KeyboardReport_Data_t
* ReportData
) 
 320         uint8_t JoyStatus_LCL 
= Joystick_GetStatus(); 
 322         /* Clear the report contents */ 
 323         memset(ReportData
, 0, sizeof(USB_KeyboardReport_Data_t
)); 
 325         if (JoyStatus_LCL 
& JOY_UP
) 
 326           ReportData
->KeyCode
[0] = 0x04; // A 
 327         else if (JoyStatus_LCL 
& JOY_DOWN
) 
 328           ReportData
->KeyCode
[0] = 0x05; // B 
 330         if (JoyStatus_LCL 
& JOY_LEFT
) 
 331           ReportData
->KeyCode
[0] = 0x06; // C 
 332         else if (JoyStatus_LCL 
& JOY_RIGHT
) 
 333           ReportData
->KeyCode
[0] = 0x07; // D 
 335         if (JoyStatus_LCL 
& JOY_PRESS
) 
 336           ReportData
->KeyCode
[0] = 0x08; // E 
 339 /** Processes a received LED report, and updates the board LEDs states to match. 
 341  *  \param LEDReport  LED status report from the host 
 343 void ProcessLEDReport(uint8_t LEDReport
) 
 345         uint8_t LEDMask 
= LEDS_LED2
; 
 347         if (LEDReport 
& 0x01) // NUM Lock 
 348           LEDMask 
|= LEDS_LED1
; 
 350         if (LEDReport 
& 0x02) // CAPS Lock 
 351           LEDMask 
|= LEDS_LED3
; 
 353         if (LEDReport 
& 0x04) // SCROLL Lock 
 354           LEDMask 
|= LEDS_LED4
; 
 356         /* Set the status LEDs to the current Keyboard LED status */ 
 357         LEDs_SetAllLEDs(LEDMask
); 
 360 /** Sends the next HID report to the host, via the keyboard data endpoint. */ 
 361 static inline void SendNextReport(void) 
 363         static USB_KeyboardReport_Data_t PrevKeyboardReportData
; 
 364         USB_KeyboardReport_Data_t        KeyboardReportData
; 
 365         bool                             SendReport 
= true; 
 367         /* Create the next keyboard report for transmission to the host */ 
 368         CreateKeyboardReport(&KeyboardReportData
); 
 370         /* Check if the idle period is set */ 
 373                 /* Check if idle period has elapsed */ 
 374                 if (!(IdleMSRemaining
)) 
 376                         /* Reset the idle time remaining counter, must multiply by 4 to get the duration in milliseconds */ 
 377                         IdleMSRemaining 
= (IdleCount 
<< 2); 
 381                         /* Idle period not elapsed, indicate that a report must not be sent unless the report has changed */ 
 382                         SendReport 
= (memcmp(&PrevKeyboardReportData
, &KeyboardReportData
, sizeof(USB_KeyboardReport_Data_t
)) != 0); 
 386         /* Save the current report data for later comparison to check for changes */ 
 387         PrevKeyboardReportData 
= KeyboardReportData
; 
 389         /* Select the Keyboard Report Endpoint */ 
 390         Endpoint_SelectEndpoint(KEYBOARD_EPNUM
); 
 392         /* Check if Keyboard Endpoint Ready for Read/Write, and if we should send a report */ 
 393         if (Endpoint_IsReadWriteAllowed() && SendReport
) 
 395                 /* Write Keyboard Report Data */ 
 396                 Endpoint_Write_Stream_LE(&KeyboardReportData
, sizeof(KeyboardReportData
)); 
 398                 /* Finalize the stream transfer to send the last packet */ 
 403 /** Reads the next LED status report from the host from the LED data endpoint, if one has been sent. */ 
 404 static inline void ReceiveNextReport(void) 
 406         /* Select the Keyboard LED Report Endpoint */ 
 407         Endpoint_SelectEndpoint(KEYBOARD_LEDS_EPNUM
); 
 409         /* Check if Keyboard LED Endpoint contains a packet */ 
 410         if (Endpoint_IsOUTReceived()) 
 412                 /* Check to see if the packet contains data */ 
 413                 if (Endpoint_IsReadWriteAllowed()) 
 415                         /* Read in the LED report from the host */ 
 416                         uint8_t LEDReport 
= Endpoint_Read_Byte(); 
 418                         /* Process the read LED report from the host */ 
 419                         ProcessLEDReport(LEDReport
); 
 422                 /* Handshake the OUT Endpoint - clear endpoint and ready for next report */ 
 427 /** Function to manage status updates to the user. This is done via LEDs on the given board, if available, but may be changed to 
 428  *  log to a serial port, or anything else that is suitable for status updates. 
 430  *  \param CurrentStatus  Current status of the system, from the Keyboard_StatusCodes_t enum 
 432 void UpdateStatus(uint8_t CurrentStatus
) 
 434         uint8_t LEDMask 
= LEDS_NO_LEDS
; 
 436         /* Set the LED mask to the appropriate LED mask based on the given status code */ 
 437         switch (CurrentStatus
) 
 439                 case Status_USBNotReady
: 
 440                         LEDMask 
= (LEDS_LED1
); 
 442                 case Status_USBEnumerating
: 
 443                         LEDMask 
= (LEDS_LED1 
| LEDS_LED2
); 
 445                 case Status_USBReady
: 
 446                         LEDMask 
= (LEDS_LED2 
| LEDS_LED4
); 
 450         /* Set the board LEDs to the new LED mask */ 
 451         LEDs_SetAllLEDs(LEDMask
); 
 454 #if !defined(INTERRUPT_DATA_ENDPOINT) 
 455 /** Function to manage HID report generation and transmission to the host, when in report mode. */ 
 456 TASK(USB_Keyboard_Report
) 
 458         /* Check if the USB system is connected to a host */ 
 461                 /* Send the next keypress report to the host */ 
 464                 /* Process the LED report sent from the host */ 
 470 /** ISR for the general Pipe/Endpoint interrupt vector. This ISR fires when an endpoint's status changes (such as 
 471  *  a packet has been received) on an endpoint with its corresponding ISR enabling bits set. This is used to send 
 472  *  HID packets to the host each time the HID interrupt endpoints polling period elapses, as managed by the USB 
 473  *  controller. It is also used to respond to standard and class specific requests send to the device on the control 
 474  *  endpoint, by handing them off to the LUFA library when they are received. 
 476 ISR(ENDPOINT_PIPE_vect
, ISR_BLOCK
) 
 478         #if defined(INTERRUPT_CONTROL_ENDPOINT) 
 479         /* Check if the control endpoint has received a request */ 
 480         if (Endpoint_HasEndpointInterrupted(ENDPOINT_CONTROLEP
)) 
 482                 /* Clear the endpoint interrupt */ 
 483                 Endpoint_ClearEndpointInterrupt(ENDPOINT_CONTROLEP
); 
 485                 /* Process the control request */ 
 488                 /* Handshake the endpoint setup interrupt - must be after the call to USB_USBTask() */ 
 489                 USB_INT_Clear(ENDPOINT_INT_SETUP
); 
 493         #if defined(INTERRUPT_DATA_ENDPOINT) 
 494         /* Check if keyboard endpoint has interrupted */ 
 495         if (Endpoint_HasEndpointInterrupted(KEYBOARD_EPNUM
)) 
 497                 /* Select the Keyboard Report Endpoint */ 
 498                 Endpoint_SelectEndpoint(KEYBOARD_EPNUM
); 
 500                 /* Clear the endpoint IN interrupt flag */ 
 501                 USB_INT_Clear(ENDPOINT_INT_IN
); 
 503                 /* Clear the Keyboard Report endpoint interrupt */ 
 504                 Endpoint_ClearEndpointInterrupt(KEYBOARD_EPNUM
); 
 506                 /* Send the next keypress report to the host */ 
 510         /* Check if Keyboard LED status Endpoint has interrupted */ 
 511         if (Endpoint_HasEndpointInterrupted(KEYBOARD_LEDS_EPNUM
)) 
 513                 /* Select the Keyboard LED Report Endpoint */ 
 514                 Endpoint_SelectEndpoint(KEYBOARD_LEDS_EPNUM
); 
 516                 /* Clear the endpoint OUT interrupt flag */ 
 517                 USB_INT_Clear(ENDPOINT_INT_OUT
); 
 519                 /* Clear the Keyboard LED Report endpoint interrupt */ 
 520                 Endpoint_ClearEndpointInterrupt(KEYBOARD_LEDS_EPNUM
); 
 522                 /* Process the LED report sent from the host */