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 /* Global Variables */
41 /** Indicates what report mode the host has requested, true for normal HID reporting mode, false for special boot
42 * protocol reporting mode.
44 bool UsingReportProtocol
= true;
46 /** Current Idle period. This is set by the host via a Set Idle HID class request to silence the device's reports
47 * for either the entire idle duration, or until the report status changes (e.g. the user presses a key).
49 uint16_t IdleCount
= 500;
51 /** Current Idle period remaining. When the IdleCount value is set, this tracks the remaining number of idle
52 * milliseconds. This is separate to the IdleCount timer and is incremented and compared as the host may request
53 * the current idle period via a Get Idle HID class request, thus its value must be preserved.
55 uint16_t IdleMSRemaining
= 0;
58 /** Main program entry point. This routine configures the hardware required by the application, then
59 * starts the scheduler to run the USB management task.
65 LEDs_SetAllLEDs(LEDMASK_USB_NOTREADY
);
74 /** Configures the board hardware and chip peripherals for the demo's functionality. */
75 void SetupHardware(void)
77 /* Disable watchdog if enabled by bootloader/fuses */
78 MCUSR
&= ~(1 << WDRF
);
81 /* Disable clock division */
82 clock_prescale_set(clock_div_1
);
84 /* Hardware Initialization */
89 /* Millisecond timer initialization, with output compare interrupt enabled for the idle timing */
91 TCCR0A
= (1 << WGM01
);
92 TCCR0B
= ((1 << CS01
) | (1 << CS00
));
93 TIMSK0
= (1 << OCIE0A
);
96 /** Event handler for the USB_Connect event. This indicates that the device is enumerating via the status LEDs and
97 * starts the library USB task to begin the enumeration and USB management process.
99 void EVENT_USB_Connect(void)
101 /* Indicate USB enumerating */
102 LEDs_SetAllLEDs(LEDMASK_USB_ENUMERATING
);
104 /* Default to report protocol on connect */
105 UsingReportProtocol
= true;
108 /** Event handler for the USB_Disconnect event. This indicates that the device is no longer connected to a host via
111 void EVENT_USB_Disconnect(void)
113 /* Indicate USB not ready */
114 LEDs_SetAllLEDs(LEDMASK_USB_NOTREADY
);
117 /** Event handler for the USB_ConfigurationChanged event. This is fired when the host sets the current configuration
118 * of the USB device after enumeration, and configures the keyboard device endpoints.
120 void EVENT_USB_ConfigurationChanged(void)
122 /* Setup Keyboard Keycode Report Endpoint */
123 Endpoint_ConfigureEndpoint(KEYBOARD_EPNUM
, EP_TYPE_INTERRUPT
,
124 ENDPOINT_DIR_IN
, KEYBOARD_EPSIZE
,
125 ENDPOINT_BANK_SINGLE
);
127 /* Setup Keyboard LED Report Endpoint */
128 Endpoint_ConfigureEndpoint(KEYBOARD_LEDS_EPNUM
, EP_TYPE_INTERRUPT
,
129 ENDPOINT_DIR_OUT
, KEYBOARD_EPSIZE
,
130 ENDPOINT_BANK_SINGLE
);
132 /* Indicate USB connected and ready */
133 LEDs_SetAllLEDs(LEDMASK_USB_READY
);
136 /** Event handler for the USB_UnhandledControlPacket event. This is used to catch standard and class specific
137 * control requests that are not handled internally by the USB library (including the HID commands, which are
138 * all issued via the control endpoint), so that they can be handled appropriately for the application.
140 void EVENT_USB_UnhandledControlPacket(void)
142 /* Handle HID Class specific requests */
143 switch (USB_ControlRequest
.bRequest
)
146 if (USB_ControlRequest
.bmRequestType
== (REQDIR_DEVICETOHOST
| REQTYPE_CLASS
| REQREC_INTERFACE
))
148 USB_KeyboardReport_Data_t KeyboardReportData
;
150 Endpoint_ClearSETUP();
152 /* Create the next keyboard report for transmission to the host */
153 CreateKeyboardReport(&KeyboardReportData
);
155 /* Write the report data to the control endpoint */
156 Endpoint_Write_Control_Stream_LE(&KeyboardReportData
, sizeof(KeyboardReportData
));
158 /* Finalize the stream transfer to send the last packet or clear the host abort */
164 if (USB_ControlRequest
.bmRequestType
== (REQDIR_HOSTTODEVICE
| REQTYPE_CLASS
| REQREC_INTERFACE
))
166 Endpoint_ClearSETUP();
168 /* Wait until the LED report has been sent by the host */
169 while (!(Endpoint_IsOUTReceived()));
171 /* Read in the LED report from the host */
172 uint8_t LEDStatus
= Endpoint_Read_Byte();
174 /* Process the incoming LED report */
175 ProcessLEDReport(LEDStatus
);
177 /* Clear the endpoint data */
180 /* Acknowledge status stage */
181 while (!(Endpoint_IsINReady()));
186 case REQ_GetProtocol
:
187 if (USB_ControlRequest
.bmRequestType
== (REQDIR_DEVICETOHOST
| REQTYPE_CLASS
| REQREC_INTERFACE
))
189 Endpoint_ClearSETUP();
191 /* Write the current protocol flag to the host */
192 Endpoint_Write_Byte(UsingReportProtocol
);
194 /* Send the flag to the host */
197 /* Acknowledge status stage */
198 while (!(Endpoint_IsOUTReceived()));
203 case REQ_SetProtocol
:
204 if (USB_ControlRequest
.bmRequestType
== (REQDIR_HOSTTODEVICE
| REQTYPE_CLASS
| REQREC_INTERFACE
))
206 Endpoint_ClearSETUP();
208 /* Set or clear the flag depending on what the host indicates that the current Protocol should be */
209 UsingReportProtocol
= (USB_ControlRequest
.wValue
!= 0);
211 /* Acknowledge status stage */
212 while (!(Endpoint_IsINReady()));
218 if (USB_ControlRequest
.bmRequestType
== (REQDIR_HOSTTODEVICE
| REQTYPE_CLASS
| REQREC_INTERFACE
))
220 Endpoint_ClearSETUP();
222 /* Get idle period in MSB */
223 IdleCount
= (USB_ControlRequest
.wValue
>> 8);
225 /* Acknowledge status stage */
226 while (!(Endpoint_IsINReady()));
232 if (USB_ControlRequest
.bmRequestType
== (REQDIR_DEVICETOHOST
| REQTYPE_CLASS
| REQREC_INTERFACE
))
234 Endpoint_ClearSETUP();
236 /* Write the current idle duration to the host */
237 Endpoint_Write_Byte(IdleCount
);
239 /* Send the flag to the host */
242 /* Acknowledge status stage */
243 while (!(Endpoint_IsOUTReceived()));
251 /** ISR for the timer 0 compare vector. This ISR fires once each millisecond, and increments the
252 * scheduler elapsed idle period counter when the host has set an idle period.
254 ISR(TIMER0_COMPA_vect
, ISR_BLOCK
)
256 /* One millisecond has elapsed, decrement the idle time remaining counter if it has not already elapsed */
261 /** Fills the given HID report data structure with the next HID report to send to the host.
263 * \param ReportData Pointer to a HID report data structure to be filled
265 void CreateKeyboardReport(USB_KeyboardReport_Data_t
* ReportData
)
267 uint8_t JoyStatus_LCL
= Joystick_GetStatus();
269 /* Clear the report contents */
270 memset(ReportData
, 0, sizeof(USB_KeyboardReport_Data_t
));
272 if (JoyStatus_LCL
& JOY_UP
)
273 ReportData
->KeyCode
[0] = 0x04; // A
274 else if (JoyStatus_LCL
& JOY_DOWN
)
275 ReportData
->KeyCode
[0] = 0x05; // B
277 if (JoyStatus_LCL
& JOY_LEFT
)
278 ReportData
->KeyCode
[0] = 0x06; // C
279 else if (JoyStatus_LCL
& JOY_RIGHT
)
280 ReportData
->KeyCode
[0] = 0x07; // D
282 if (JoyStatus_LCL
& JOY_PRESS
)
283 ReportData
->KeyCode
[0] = 0x08; // E
286 /** Processes a received LED report, and updates the board LEDs states to match.
288 * \param LEDReport LED status report from the host
290 void ProcessLEDReport(uint8_t LEDReport
)
292 uint8_t LEDMask
= LEDS_LED2
;
294 if (LEDReport
& 0x01) // NUM Lock
295 LEDMask
|= LEDS_LED1
;
297 if (LEDReport
& 0x02) // CAPS Lock
298 LEDMask
|= LEDS_LED3
;
300 if (LEDReport
& 0x04) // SCROLL Lock
301 LEDMask
|= LEDS_LED4
;
303 /* Set the status LEDs to the current Keyboard LED status */
304 LEDs_SetAllLEDs(LEDMask
);
307 /** Sends the next HID report to the host, via the keyboard data endpoint. */
308 void SendNextReport(void)
310 static USB_KeyboardReport_Data_t PrevKeyboardReportData
;
311 USB_KeyboardReport_Data_t KeyboardReportData
;
312 bool SendReport
= true;
314 /* Create the next keyboard report for transmission to the host */
315 CreateKeyboardReport(&KeyboardReportData
);
317 /* Check to see if the report data has changed - if so a report MUST be sent */
318 SendReport
= (memcmp(&PrevKeyboardReportData
, &KeyboardReportData
, sizeof(USB_KeyboardReport_Data_t
)) != 0);
320 /* Save the current report data for later comparison to check for changes */
321 PrevKeyboardReportData
= KeyboardReportData
;
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, must multiply by 4 to get the duration in milliseconds */
327 IdleMSRemaining
= (IdleCount
<< 2);
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 /* Write Keyboard Report Data */
340 Endpoint_Write_Stream_LE(&KeyboardReportData
, sizeof(KeyboardReportData
));
342 /* Finalize the stream transfer to send the last packet */
347 /** Reads the next LED status report from the host from the LED data endpoint, if one has been sent. */
348 void ReceiveNextReport(void)
350 /* Select the Keyboard LED Report Endpoint */
351 Endpoint_SelectEndpoint(KEYBOARD_LEDS_EPNUM
);
353 /* Check if Keyboard LED Endpoint contains a packet */
354 if (Endpoint_IsOUTReceived())
356 /* Check to see if the packet contains data */
357 if (Endpoint_IsReadWriteAllowed())
359 /* Read in the LED report from the host */
360 uint8_t LEDReport
= Endpoint_Read_Byte();
362 /* Process the read LED report from the host */
363 ProcessLEDReport(LEDReport
);
366 /* Handshake the OUT Endpoint - clear endpoint and ready for next report */
371 /** Function to manage HID report generation and transmission to the host, when in report mode. */
374 /* Check if the USB system is connected to a host */
377 /* Send the next keypress report to the host */
380 /* Process the LED report sent from the host */