3 Copyright (C) Dean Camera, 2010.
5 dean [at] fourwalledcubicle [dot] com
6 www.fourwalledcubicle.com
10 Copyright 2010 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, distribute, and sell this
14 software and its documentation for any purpose is hereby granted
15 without fee, provided that the above copyright notice appear in
16 all 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 */
90 /** Event handler for the USB_Connect event. This indicates that the device is enumerating via the status LEDs and
91 * starts the library USB task to begin the enumeration and USB management process.
93 void EVENT_USB_Device_Connect(void)
95 /* Indicate USB enumerating */
96 LEDs_SetAllLEDs(LEDMASK_USB_ENUMERATING
);
98 /* Default to report protocol on connect */
99 UsingReportProtocol
= true;
102 /** Event handler for the USB_Disconnect event. This indicates that the device is no longer connected to a host via
105 void EVENT_USB_Device_Disconnect(void)
107 /* Indicate USB not ready */
108 LEDs_SetAllLEDs(LEDMASK_USB_NOTREADY
);
111 /** Event handler for the USB_ConfigurationChanged event. This is fired when the host sets the current configuration
112 * of the USB device after enumeration, and configures the keyboard device endpoints.
114 void EVENT_USB_Device_ConfigurationChanged(void)
116 /* Indicate USB connected and ready */
117 LEDs_SetAllLEDs(LEDMASK_USB_READY
);
119 /* Setup Keyboard Keycode Report Endpoint */
120 if (!(Endpoint_ConfigureEndpoint(KEYBOARD_EPNUM
, EP_TYPE_INTERRUPT
,
121 ENDPOINT_DIR_IN
, KEYBOARD_EPSIZE
,
122 ENDPOINT_BANK_SINGLE
)))
124 LEDs_SetAllLEDs(LEDMASK_USB_ERROR
);
127 /* Setup Keyboard LED Report Endpoint */
128 if (!(Endpoint_ConfigureEndpoint(KEYBOARD_LEDS_EPNUM
, EP_TYPE_INTERRUPT
,
129 ENDPOINT_DIR_OUT
, KEYBOARD_EPSIZE
,
130 ENDPOINT_BANK_SINGLE
)))
132 LEDs_SetAllLEDs(LEDMASK_USB_ERROR
);
135 USB_Device_EnableSOFEvents();
138 /** Event handler for the USB_UnhandledControlRequest event. This is used to catch standard and class specific
139 * control requests that are not handled internally by the USB library (including the HID commands, which are
140 * all issued via the control endpoint), so that they can be handled appropriately for the application.
142 void EVENT_USB_Device_UnhandledControlRequest(void)
144 /* Handle HID Class specific requests */
145 switch (USB_ControlRequest
.bRequest
)
148 if (USB_ControlRequest
.bmRequestType
== (REQDIR_DEVICETOHOST
| REQTYPE_CLASS
| REQREC_INTERFACE
))
150 USB_KeyboardReport_Data_t KeyboardReportData
;
152 Endpoint_ClearSETUP();
154 /* Create the next keyboard report for transmission to the host */
155 CreateKeyboardReport(&KeyboardReportData
);
157 /* Write the report data to the control endpoint */
158 Endpoint_Write_Control_Stream_LE(&KeyboardReportData
, sizeof(KeyboardReportData
));
160 /* Finalize the stream transfer to send the last packet or clear the host abort */
166 if (USB_ControlRequest
.bmRequestType
== (REQDIR_HOSTTODEVICE
| REQTYPE_CLASS
| REQREC_INTERFACE
))
168 Endpoint_ClearSETUP();
170 /* Wait until the LED report has been sent by the host */
171 while (!(Endpoint_IsOUTReceived()))
173 if (USB_DeviceState
== DEVICE_STATE_Unattached
)
177 /* Read in the LED report from the host */
178 uint8_t LEDStatus
= Endpoint_Read_Byte();
180 /* Process the incoming LED report */
181 ProcessLEDReport(LEDStatus
);
183 /* Clear the endpoint data */
186 Endpoint_ClearStatusStage();
190 case REQ_GetProtocol
:
191 if (USB_ControlRequest
.bmRequestType
== (REQDIR_DEVICETOHOST
| REQTYPE_CLASS
| REQREC_INTERFACE
))
193 Endpoint_ClearSETUP();
195 /* Write the current protocol flag to the host */
196 Endpoint_Write_Byte(UsingReportProtocol
);
198 /* Send the flag to the host */
201 Endpoint_ClearStatusStage();
205 case REQ_SetProtocol
:
206 if (USB_ControlRequest
.bmRequestType
== (REQDIR_HOSTTODEVICE
| REQTYPE_CLASS
| REQREC_INTERFACE
))
208 Endpoint_ClearSETUP();
210 /* Set or clear the flag depending on what the host indicates that the current Protocol should be */
211 UsingReportProtocol
= (USB_ControlRequest
.wValue
!= 0);
213 Endpoint_ClearStatusStage();
218 if (USB_ControlRequest
.bmRequestType
== (REQDIR_HOSTTODEVICE
| REQTYPE_CLASS
| REQREC_INTERFACE
))
220 Endpoint_ClearSETUP();
222 /* Get idle period in MSB, IdleCount must be multiplied by 4 to get number of milliseconds */
223 IdleCount
= ((USB_ControlRequest
.wValue
& 0xFF00) >> 6);
225 Endpoint_ClearStatusStage();
230 if (USB_ControlRequest
.bmRequestType
== (REQDIR_DEVICETOHOST
| REQTYPE_CLASS
| REQREC_INTERFACE
))
232 Endpoint_ClearSETUP();
234 /* Write the current idle duration to the host, must be divided by 4 before sent to host */
235 Endpoint_Write_Byte(IdleCount
>> 2);
237 /* Send the flag to the host */
240 Endpoint_ClearStatusStage();
247 /** Event handler for the USB device Start Of Frame event. */
248 void EVENT_USB_Device_StartOfFrame(void)
250 /* One millisecond has elapsed, decrement the idle time remaining counter if it has not already elapsed */
255 /** Fills the given HID report data structure with the next HID report to send to the host.
257 * \param[out] ReportData Pointer to a HID report data structure to be filled
259 void CreateKeyboardReport(USB_KeyboardReport_Data_t
* ReportData
)
261 uint8_t JoyStatus_LCL
= Joystick_GetStatus();
262 uint8_t ButtonStatus_LCL
= Buttons_GetStatus();
264 uint8_t UsedKeyCodes
= 0;
266 /* Clear the report contents */
267 memset(ReportData
, 0, sizeof(USB_KeyboardReport_Data_t
));
269 /* Make sent key uppercase by indicating that the left shift key is pressed */
270 ReportData
->Modifier
= KEYBOARD_MODIFER_LEFTSHIFT
;
272 if (JoyStatus_LCL
& JOY_UP
)
273 ReportData
->KeyCode
[UsedKeyCodes
++] = 0x04; // A
274 else if (JoyStatus_LCL
& JOY_DOWN
)
275 ReportData
->KeyCode
[UsedKeyCodes
++] = 0x05; // B
277 if (JoyStatus_LCL
& JOY_LEFT
)
278 ReportData
->KeyCode
[UsedKeyCodes
++] = 0x06; // C
279 else if (JoyStatus_LCL
& JOY_RIGHT
)
280 ReportData
->KeyCode
[UsedKeyCodes
++] = 0x07; // D
282 if (JoyStatus_LCL
& JOY_PRESS
)
283 ReportData
->KeyCode
[UsedKeyCodes
++] = 0x08; // E
285 if (ButtonStatus_LCL
& BUTTONS_BUTTON1
)
286 ReportData
->KeyCode
[UsedKeyCodes
++] = 0x09; // F
289 /** Processes a received LED report, and updates the board LEDs states to match.
291 * \param[in] LEDReport LED status report from the host
293 void ProcessLEDReport(uint8_t LEDReport
)
295 uint8_t LEDMask
= LEDS_LED2
;
297 if (LEDReport
& 0x01) // NUM Lock
298 LEDMask
|= LEDS_LED1
;
300 if (LEDReport
& 0x02) // CAPS Lock
301 LEDMask
|= LEDS_LED3
;
303 if (LEDReport
& 0x04) // SCROLL Lock
304 LEDMask
|= LEDS_LED4
;
306 /* Set the status LEDs to the current Keyboard LED status */
307 LEDs_SetAllLEDs(LEDMask
);
310 /** Sends the next HID report to the host, via the keyboard data endpoint. */
311 void SendNextReport(void)
313 static USB_KeyboardReport_Data_t PrevKeyboardReportData
;
314 USB_KeyboardReport_Data_t KeyboardReportData
;
315 bool SendReport
= true;
317 /* Create the next keyboard report for transmission to the host */
318 CreateKeyboardReport(&KeyboardReportData
);
320 /* Check to see if the report data has changed - if so a report MUST be sent */
321 SendReport
= (memcmp(&PrevKeyboardReportData
, &KeyboardReportData
, sizeof(USB_KeyboardReport_Data_t
)) != 0);
323 /* Check if the idle period is set and has elapsed */
324 if ((IdleCount
!= HID_IDLE_CHANGESONLY
) && (!(IdleMSRemaining
)))
326 /* Reset the idle time remaining counter */
327 IdleMSRemaining
= IdleCount
;
329 /* Idle period is set and has elapsed, must send a report to the host */
333 /* Select the Keyboard Report Endpoint */
334 Endpoint_SelectEndpoint(KEYBOARD_EPNUM
);
336 /* Check if Keyboard Endpoint Ready for Read/Write and if we should send a new report */
337 if (Endpoint_IsReadWriteAllowed() && SendReport
)
339 /* Save the current report data for later comparison to check for changes */
340 PrevKeyboardReportData
= KeyboardReportData
;
342 /* Write Keyboard Report Data */
343 Endpoint_Write_Stream_LE(&KeyboardReportData
, sizeof(KeyboardReportData
));
345 /* Finalize the stream transfer to send the last packet */
350 /** Reads the next LED status report from the host from the LED data endpoint, if one has been sent. */
351 void ReceiveNextReport(void)
353 /* Select the Keyboard LED Report Endpoint */
354 Endpoint_SelectEndpoint(KEYBOARD_LEDS_EPNUM
);
356 /* Check if Keyboard LED Endpoint contains a packet */
357 if (Endpoint_IsOUTReceived())
359 /* Check to see if the packet contains data */
360 if (Endpoint_IsReadWriteAllowed())
362 /* Read in the LED report from the host */
363 uint8_t LEDReport
= Endpoint_Read_Byte();
365 /* Process the read LED report from the host */
366 ProcessLEDReport(LEDReport
);
369 /* Handshake the OUT Endpoint - clear endpoint and ready for next report */
374 /** Function to manage HID report generation and transmission to the host, when in report mode. */
377 /* Device must be connected and configured for the task to run */
378 if (USB_DeviceState
!= DEVICE_STATE_Configured
)
381 /* Send the next keypress report to the host */
384 /* Process the LED report sent from the host */