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 /** Indicates what report mode the host has requested, true for normal HID reporting mode, false for special boot 
  41  *  protocol reporting mode. 
  43 bool UsingReportProtocol 
= true; 
  45 /** Current Idle period. This is set by the host via a Set Idle HID class request to silence the device's reports 
  46  *  for either the entire idle duration, or until the report status changes (e.g. the user presses a key). 
  48 uint16_t IdleCount 
= 500; 
  50 /** Current Idle period remaining. When the IdleCount value is set, this tracks the remaining number of idle 
  51  *  milliseconds. This is separate to the IdleCount timer and is incremented and compared as the host may request  
  52  *  the current idle period via a Get Idle HID class request, thus its value must be preserved. 
  54 uint16_t IdleMSRemaining 
= 0; 
  57 /** Main program entry point. This routine configures the hardware required by the application, then 
  58  *  enters a loop to run the application tasks in sequence. 
  64         LEDs_SetAllLEDs(LEDMASK_USB_NOTREADY
); 
  73 /** Configures the board hardware and chip peripherals for the demo's functionality. */ 
  74 void SetupHardware(void) 
  76         /* Disable watchdog if enabled by bootloader/fuses */ 
  77         MCUSR 
&= ~(1 << WDRF
); 
  80         /* Disable clock division */ 
  81         clock_prescale_set(clock_div_1
); 
  83         /* Hardware Initialization */ 
  89 /** Event handler for the USB_Connect event. This indicates that the device is enumerating via the status LEDs and 
  90  *  starts the library USB task to begin the enumeration and USB management process. 
  92 void EVENT_USB_Device_Connect(void) 
  94         /* Indicate USB enumerating */ 
  95         LEDs_SetAllLEDs(LEDMASK_USB_ENUMERATING
); 
  97         /* Default to report protocol on connect */ 
  98         UsingReportProtocol 
= true; 
 101 /** Event handler for the USB_Disconnect event. This indicates that the device is no longer connected to a host via 
 104 void EVENT_USB_Device_Disconnect(void) 
 106         /* Indicate USB not ready */ 
 107         LEDs_SetAllLEDs(LEDMASK_USB_NOTREADY
); 
 110 /** Event handler for the USB_ConfigurationChanged event. This is fired when the host sets the current configuration 
 111  *  of the USB device after enumeration, and configures the keyboard device endpoints. 
 113 void EVENT_USB_Device_ConfigurationChanged(void) 
 115         /* Indicate USB connected and ready */ 
 116         LEDs_SetAllLEDs(LEDMASK_USB_READY
); 
 118         /* Setup Keyboard Keycode Report Endpoint */ 
 119         if (!(Endpoint_ConfigureEndpoint(KEYBOARD_EPNUM
, EP_TYPE_INTERRUPT
, 
 120                                              ENDPOINT_DIR_IN
, KEYBOARD_EPSIZE
, 
 121                                          ENDPOINT_BANK_SINGLE
))) 
 123                 LEDs_SetAllLEDs(LEDMASK_USB_ERROR
); 
 126         /* Setup Keyboard LED Report Endpoint */ 
 127         if (!(Endpoint_ConfigureEndpoint(KEYBOARD_LEDS_EPNUM
, EP_TYPE_INTERRUPT
, 
 128                                              ENDPOINT_DIR_OUT
, KEYBOARD_EPSIZE
, 
 129                                          ENDPOINT_BANK_SINGLE
))) 
 131                 LEDs_SetAllLEDs(LEDMASK_USB_ERROR
); 
 134         USB_Device_EnableSOFEvents(); 
 137 /** Event handler for the USB_UnhandledControlRequest event. This is used to catch standard and class specific 
 138  *  control requests that are not handled internally by the USB library (including the HID commands, which are 
 139  *  all issued via the control endpoint), so that they can be handled appropriately for the application. 
 141 void EVENT_USB_Device_UnhandledControlRequest(void) 
 143         /* Handle HID Class specific requests */ 
 144         switch (USB_ControlRequest
.bRequest
) 
 147                         if (USB_ControlRequest
.bmRequestType 
== (REQDIR_DEVICETOHOST 
| REQTYPE_CLASS 
| REQREC_INTERFACE
)) 
 149                                 USB_KeyboardReport_Data_t KeyboardReportData
; 
 151                                 Endpoint_ClearSETUP(); 
 153                                 /* Create the next keyboard report for transmission to the host */ 
 154                                 CreateKeyboardReport(&KeyboardReportData
); 
 156                                 /* Write the report data to the control endpoint */ 
 157                                 Endpoint_Write_Control_Stream_LE(&KeyboardReportData
, sizeof(KeyboardReportData
)); 
 159                                 /* Finalize the stream transfer to send the last packet or clear the host abort */ 
 165                         if (USB_ControlRequest
.bmRequestType 
== (REQDIR_HOSTTODEVICE 
| REQTYPE_CLASS 
| REQREC_INTERFACE
)) 
 167                                 Endpoint_ClearSETUP(); 
 169                                 /* Wait until the LED report has been sent by the host */ 
 170                                 while (!(Endpoint_IsOUTReceived())) 
 172                                         if (USB_DeviceState 
== DEVICE_STATE_Unattached
) 
 176                                 /* Read in the LED report from the host */ 
 177                                 uint8_t LEDStatus 
= Endpoint_Read_Byte(); 
 179                                 /* Process the incoming LED report */ 
 180                                 ProcessLEDReport(LEDStatus
); 
 182                                 /* Clear the endpoint data */ 
 185                                 Endpoint_ClearStatusStage(); 
 189                 case REQ_GetProtocol
: 
 190                         if (USB_ControlRequest
.bmRequestType 
== (REQDIR_DEVICETOHOST 
| REQTYPE_CLASS 
| REQREC_INTERFACE
)) 
 192                                 Endpoint_ClearSETUP(); 
 194                                 /* Write the current protocol flag to the host */ 
 195                                 Endpoint_Write_Byte(UsingReportProtocol
); 
 197                                 /* Send the flag to the host */ 
 200                                 Endpoint_ClearStatusStage(); 
 204                 case REQ_SetProtocol
: 
 205                         if (USB_ControlRequest
.bmRequestType 
== (REQDIR_HOSTTODEVICE 
| REQTYPE_CLASS 
| REQREC_INTERFACE
)) 
 207                                 Endpoint_ClearSETUP(); 
 209                                 /* Set or clear the flag depending on what the host indicates that the current Protocol should be */ 
 210                                 UsingReportProtocol 
= (USB_ControlRequest
.wValue 
!= 0); 
 212                                 Endpoint_ClearStatusStage(); 
 217                         if (USB_ControlRequest
.bmRequestType 
== (REQDIR_HOSTTODEVICE 
| REQTYPE_CLASS 
| REQREC_INTERFACE
)) 
 219                                 Endpoint_ClearSETUP(); 
 221                                 /* Get idle period in MSB, IdleCount must be multiplied by 4 to get number of milliseconds */ 
 222                                 IdleCount 
= ((USB_ControlRequest
.wValue 
& 0xFF00) >> 6); 
 224                                 Endpoint_ClearStatusStage(); 
 229                         if (USB_ControlRequest
.bmRequestType 
== (REQDIR_DEVICETOHOST 
| REQTYPE_CLASS 
| REQREC_INTERFACE
)) 
 231                                 Endpoint_ClearSETUP(); 
 233                                 /* Write the current idle duration to the host, must be divided by 4 before sent to host */ 
 234                                 Endpoint_Write_Byte(IdleCount 
>> 2); 
 236                                 /* Send the flag to the host */ 
 239                                 Endpoint_ClearStatusStage(); 
 246 /** Event handler for the USB device Start Of Frame event. */ 
 247 void EVENT_USB_Device_StartOfFrame(void) 
 249         /* One millisecond has elapsed, decrement the idle time remaining counter if it has not already elapsed */ 
 254 /** Fills the given HID report data structure with the next HID report to send to the host. 
 256  *  \param[out] ReportData  Pointer to a HID report data structure to be filled 
 258 void CreateKeyboardReport(USB_KeyboardReport_Data_t
* ReportData
) 
 260         uint8_t JoyStatus_LCL 
= Joystick_GetStatus(); 
 262         /* Clear the report contents */ 
 263         memset(ReportData
, 0, sizeof(USB_KeyboardReport_Data_t
)); 
 265         if (JoyStatus_LCL 
& JOY_UP
) 
 266           ReportData
->KeyCode
[0] = 0x04; // A 
 267         else if (JoyStatus_LCL 
& JOY_DOWN
) 
 268           ReportData
->KeyCode
[0] = 0x05; // B 
 270         if (JoyStatus_LCL 
& JOY_LEFT
) 
 271           ReportData
->KeyCode
[0] = 0x06; // C 
 272         else if (JoyStatus_LCL 
& JOY_RIGHT
) 
 273           ReportData
->KeyCode
[0] = 0x07; // D 
 275         if (JoyStatus_LCL 
& JOY_PRESS
) 
 276           ReportData
->KeyCode
[0] = 0x08; // E 
 279 /** Processes a received LED report, and updates the board LEDs states to match. 
 281  *  \param[in] LEDReport  LED status report from the host 
 283 void ProcessLEDReport(uint8_t LEDReport
) 
 285         uint8_t LEDMask 
= LEDS_LED2
; 
 287         if (LEDReport 
& 0x01) // NUM Lock 
 288           LEDMask 
|= LEDS_LED1
; 
 290         if (LEDReport 
& 0x02) // CAPS Lock 
 291           LEDMask 
|= LEDS_LED3
; 
 293         if (LEDReport 
& 0x04) // SCROLL Lock 
 294           LEDMask 
|= LEDS_LED4
; 
 296         /* Set the status LEDs to the current Keyboard LED status */ 
 297         LEDs_SetAllLEDs(LEDMask
); 
 300 /** Sends the next HID report to the host, via the keyboard data endpoint. */ 
 301 void SendNextReport(void) 
 303         static USB_KeyboardReport_Data_t PrevKeyboardReportData
; 
 304         USB_KeyboardReport_Data_t        KeyboardReportData
; 
 305         bool                             SendReport 
= true; 
 307         /* Create the next keyboard report for transmission to the host */ 
 308         CreateKeyboardReport(&KeyboardReportData
); 
 310         /* Check to see if the report data has changed - if so a report MUST be sent */ 
 311         SendReport 
= (memcmp(&PrevKeyboardReportData
, &KeyboardReportData
, sizeof(USB_KeyboardReport_Data_t
)) != 0); 
 313         /* Save the current report data for later comparison to check for changes */ 
 314         PrevKeyboardReportData 
= KeyboardReportData
; 
 316         /* Check if the idle period is set and has elapsed */ 
 317         if ((IdleCount 
!= HID_IDLE_CHANGESONLY
) && (!(IdleMSRemaining
))) 
 319                 /* Reset the idle time remaining counter */ 
 320                 IdleMSRemaining 
= IdleCount
; 
 322                 /* Idle period is set and has elapsed, must send a report to the host */ 
 326         /* Select the Keyboard Report Endpoint */ 
 327         Endpoint_SelectEndpoint(KEYBOARD_EPNUM
); 
 329         /* Check if Keyboard Endpoint Ready for Read/Write and if we should send a new report */ 
 330         if (Endpoint_IsReadWriteAllowed() && SendReport
) 
 332                 /* Write Keyboard Report Data */ 
 333                 Endpoint_Write_Stream_LE(&KeyboardReportData
, sizeof(KeyboardReportData
)); 
 335                 /* Finalize the stream transfer to send the last packet */ 
 340 /** Reads the next LED status report from the host from the LED data endpoint, if one has been sent. */ 
 341 void ReceiveNextReport(void) 
 343         /* Select the Keyboard LED Report Endpoint */ 
 344         Endpoint_SelectEndpoint(KEYBOARD_LEDS_EPNUM
); 
 346         /* Check if Keyboard LED Endpoint contains a packet */ 
 347         if (Endpoint_IsOUTReceived()) 
 349                 /* Check to see if the packet contains data */ 
 350                 if (Endpoint_IsReadWriteAllowed()) 
 352                         /* Read in the LED report from the host */ 
 353                         uint8_t LEDReport 
= Endpoint_Read_Byte(); 
 355                         /* Process the read LED report from the host */ 
 356                         ProcessLEDReport(LEDReport
); 
 359                 /* Handshake the OUT Endpoint - clear endpoint and ready for next report */ 
 364 /** Function to manage HID report generation and transmission to the host, when in report mode. */ 
 367         /* Device must be connected and configured for the task to run */ 
 368         if (USB_DeviceState 
!= DEVICE_STATE_Configured
) 
 371         /* Send the next keypress report to the host */ 
 374         /* Process the LED report sent from the host */