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 { .Task
= USB_Keyboard_Report
, .TaskStatus
= TASK_STOP
},
50 /* Global Variables */
51 /** Indicates what report mode the host has requested, true for normal HID reporting mode, false for special boot
52 * protocol reporting mode.
54 bool UsingReportProtocol
= true;
56 /** Current Idle period. This is set by the host via a Set Idle HID class request to silence the device's reports
57 * for either the entire idle duration, or until the report status changes (e.g. the user presses a key).
59 uint16_t IdleCount
= 500;
61 /** Current Idle period remaining. When the IdleCount value is set, this tracks the remaining number of idle
62 * milliseconds. This is separate to the IdleCount timer and is incremented and compared as the host may request
63 * the current idle period via a Get Idle HID class request, thus its value must be preserved.
65 uint16_t IdleMSRemaining
= 0;
68 /** Main program entry point. This routine configures the hardware required by the application, then
69 * starts the scheduler to run the USB management task.
73 /* Disable watchdog if enabled by bootloader/fuses */
74 MCUSR
&= ~(1 << WDRF
);
77 /* Disable clock division */
78 clock_prescale_set(clock_div_1
);
80 /* Hardware Initialization */
84 /* Millisecond timer initialization, with output compare interrupt enabled for the idle timing */
86 TCCR0A
= (1 << WGM01
);
87 TCCR0B
= ((1 << CS01
) | (1 << CS00
));
88 TIMSK0
= (1 << OCIE0A
);
90 /* Indicate USB not ready */
91 UpdateStatus(Status_USBNotReady
);
93 /* Initialize Scheduler so that it can be used */
96 /* Initialize USB Subsystem */
99 /* Scheduling - routine never returns, so put this last in the main function */
103 /** Event handler for the USB_Connect event. This indicates that the device is enumerating via the status LEDs and
104 * starts the library USB task to begin the enumeration and USB management process.
106 EVENT_HANDLER(USB_Connect
)
108 #if !defined(INTERRUPT_CONTROL_ENDPOINT)
109 /* Start USB management task */
110 Scheduler_SetTaskMode(USB_USBTask
, TASK_RUN
);
113 /* Indicate USB enumerating */
114 UpdateStatus(Status_USBEnumerating
);
116 /* Default to report protocol on connect */
117 UsingReportProtocol
= true;
120 /** Event handler for the USB_Reset event. This fires when the USB interface is reset by the USB host, before the
121 * enumeration process begins, and enables the control endpoint interrupt so that control requests can be handled
122 * asynchronously when they arrive rather than when the control endpoint is polled manually.
124 EVENT_HANDLER(USB_Reset
)
126 #if defined(INTERRUPT_CONTROL_ENDPOINT)
127 /* Select the control endpoint */
128 Endpoint_SelectEndpoint(ENDPOINT_CONTROLEP
);
130 /* Enable the endpoint SETUP interrupt ISR for the control endpoint */
131 USB_INT_Enable(ENDPOINT_INT_SETUP
);
135 /** Event handler for the USB_Disconnect event. This indicates that the device is no longer connected to a host via
138 EVENT_HANDLER(USB_Disconnect
)
140 /* Stop running keyboard reporting and USB management tasks */
141 Scheduler_SetTaskMode(USB_Keyboard_Report
, TASK_STOP
);
143 #if !defined(INTERRUPT_CONTROL_ENDPOINT)
144 Scheduler_SetTaskMode(USB_USBTask
, TASK_STOP
);
147 /* Indicate USB not ready */
148 UpdateStatus(Status_USBNotReady
);
151 /** Event handler for the USB_ConfigurationChanged event. This is fired when the host sets the current configuration
152 * of the USB device after enumeration, and configures the keyboard device endpoints.
154 EVENT_HANDLER(USB_ConfigurationChanged
)
156 /* Setup Keyboard Keycode Report Endpoint */
157 Endpoint_ConfigureEndpoint(KEYBOARD_EPNUM
, EP_TYPE_INTERRUPT
,
158 ENDPOINT_DIR_IN
, KEYBOARD_EPSIZE
,
159 ENDPOINT_BANK_SINGLE
);
161 /* Setup Keyboard LED Report Endpoint */
162 Endpoint_ConfigureEndpoint(KEYBOARD_LEDS_EPNUM
, EP_TYPE_INTERRUPT
,
163 ENDPOINT_DIR_OUT
, KEYBOARD_EPSIZE
,
164 ENDPOINT_BANK_SINGLE
);
166 /* Indicate USB connected and ready */
167 UpdateStatus(Status_USBReady
);
169 /* Start running keyboard reporting task */
170 Scheduler_SetTaskMode(USB_Keyboard_Report
, TASK_RUN
);
173 /** Event handler for the USB_UnhandledControlPacket event. This is used to catch standard and class specific
174 * control requests that are not handled internally by the USB library (including the HID commands, which are
175 * all issued via the control endpoint), so that they can be handled appropriately for the application.
177 EVENT_HANDLER(USB_UnhandledControlPacket
)
179 /* Handle HID Class specific requests */
180 switch (USB_ControlRequest
.bRequest
)
183 if (USB_ControlRequest
.bmRequestType
== (REQDIR_DEVICETOHOST
| REQTYPE_CLASS
| REQREC_INTERFACE
))
185 USB_KeyboardReport_Data_t KeyboardReportData
;
187 Endpoint_ClearSETUP();
189 /* Create the next keyboard report for transmission to the host */
190 CreateKeyboardReport(&KeyboardReportData
);
192 /* Write the report data to the control endpoint */
193 Endpoint_Write_Control_Stream_LE(&KeyboardReportData
, sizeof(KeyboardReportData
));
195 /* Finalize the stream transfer to send the last packet or clear the host abort */
201 if (USB_ControlRequest
.bmRequestType
== (REQDIR_HOSTTODEVICE
| REQTYPE_CLASS
| REQREC_INTERFACE
))
203 Endpoint_ClearSETUP();
205 /* Wait until the LED report has been sent by the host */
206 while (!(Endpoint_IsOUTReceived()));
208 /* Read in the LED report from the host */
209 uint8_t LEDStatus
= Endpoint_Read_Byte();
211 /* Process the incoming LED report */
212 ProcessLEDReport(LEDStatus
);
214 /* Clear the endpoint data */
217 /* Acknowledge status stage */
218 while (!(Endpoint_IsINReady()));
223 case REQ_GetProtocol
:
224 if (USB_ControlRequest
.bmRequestType
== (REQDIR_DEVICETOHOST
| REQTYPE_CLASS
| REQREC_INTERFACE
))
226 Endpoint_ClearSETUP();
228 /* Write the current protocol flag to the host */
229 Endpoint_Write_Byte(UsingReportProtocol
);
231 /* Send the flag to the host */
234 /* Acknowledge status stage */
235 while (!(Endpoint_IsOUTReceived()));
240 case REQ_SetProtocol
:
241 if (USB_ControlRequest
.bmRequestType
== (REQDIR_HOSTTODEVICE
| REQTYPE_CLASS
| REQREC_INTERFACE
))
243 Endpoint_ClearSETUP();
245 /* Set or clear the flag depending on what the host indicates that the current Protocol should be */
246 UsingReportProtocol
= (USB_ControlRequest
.wValue
!= 0x0000);
248 /* Acknowledge status stage */
249 while (!(Endpoint_IsINReady()));
255 if (USB_ControlRequest
.bmRequestType
== (REQDIR_HOSTTODEVICE
| REQTYPE_CLASS
| REQREC_INTERFACE
))
257 Endpoint_ClearSETUP();
259 /* Get idle period in MSB */
260 IdleCount
= (USB_ControlRequest
.wValue
>> 8);
262 /* Acknowledge status stage */
263 while (!(Endpoint_IsINReady()));
269 if (USB_ControlRequest
.bmRequestType
== (REQDIR_DEVICETOHOST
| REQTYPE_CLASS
| REQREC_INTERFACE
))
271 Endpoint_ClearSETUP();
273 /* Write the current idle duration to the host */
274 Endpoint_Write_Byte(IdleCount
);
276 /* Send the flag to the host */
279 /* Acknowledge status stage */
280 while (!(Endpoint_IsOUTReceived()));
288 /** ISR for the timer 0 compare vector. This ISR fires once each millisecond, and increments the
289 * scheduler elapsed idle period counter when the host has set an idle period.
291 ISR(TIMER0_COMPA_vect
, ISR_BLOCK
)
293 /* One millisecond has elapsed, decrement the idle time remaining counter if it has not already elapsed */
298 /** Fills the given HID report data structure with the next HID report to send to the host.
300 * \param ReportData Pointer to a HID report data structure to be filled
302 void CreateKeyboardReport(USB_KeyboardReport_Data_t
* ReportData
)
304 uint8_t JoyStatus_LCL
= Joystick_GetStatus();
306 /* Clear the report contents */
307 memset(ReportData
, 0, sizeof(USB_KeyboardReport_Data_t
));
309 if (JoyStatus_LCL
& JOY_UP
)
310 ReportData
->KeyCode
[0] = 0x04; // A
311 else if (JoyStatus_LCL
& JOY_DOWN
)
312 ReportData
->KeyCode
[0] = 0x05; // B
314 if (JoyStatus_LCL
& JOY_LEFT
)
315 ReportData
->KeyCode
[0] = 0x06; // C
316 else if (JoyStatus_LCL
& JOY_RIGHT
)
317 ReportData
->KeyCode
[0] = 0x07; // D
319 if (JoyStatus_LCL
& JOY_PRESS
)
320 ReportData
->KeyCode
[0] = 0x08; // E
323 /** Processes a received LED report, and updates the board LEDs states to match.
325 * \param LEDReport LED status report from the host
327 void ProcessLEDReport(uint8_t LEDReport
)
329 uint8_t LEDMask
= LEDS_LED2
;
331 if (LEDReport
& 0x01) // NUM Lock
332 LEDMask
|= LEDS_LED1
;
334 if (LEDReport
& 0x02) // CAPS Lock
335 LEDMask
|= LEDS_LED3
;
337 if (LEDReport
& 0x04) // SCROLL Lock
338 LEDMask
|= LEDS_LED4
;
340 /* Set the status LEDs to the current Keyboard LED status */
341 LEDs_SetAllLEDs(LEDMask
);
344 /** Sends the next HID report to the host, via the keyboard data endpoint. */
345 void SendNextReport(void)
347 static USB_KeyboardReport_Data_t PrevKeyboardReportData
;
348 USB_KeyboardReport_Data_t KeyboardReportData
;
349 bool SendReport
= true;
351 /* Create the next keyboard report for transmission to the host */
352 CreateKeyboardReport(&KeyboardReportData
);
354 /* Check to see if the report data has changed - if so a report MUST be sent */
355 SendReport
= (memcmp(&PrevKeyboardReportData
, &KeyboardReportData
, sizeof(USB_KeyboardReport_Data_t
)) != 0);
357 /* Save the current report data for later comparison to check for changes */
358 PrevKeyboardReportData
= KeyboardReportData
;
360 /* Check if the idle period is set and has elapsed */
361 if ((IdleCount
!= HID_IDLE_CHANGESONLY
) && (!(IdleMSRemaining
)))
363 /* Reset the idle time remaining counter, must multiply by 4 to get the duration in milliseconds */
364 IdleMSRemaining
= (IdleCount
<< 2);
366 /* Idle period is set and has elapsed, must send a report to the host */
370 /* Select the Keyboard Report Endpoint */
371 Endpoint_SelectEndpoint(KEYBOARD_EPNUM
);
373 /* Check if Keyboard Endpoint Ready for Read/Write and if we should send a new report */
374 if (Endpoint_IsReadWriteAllowed() && SendReport
)
376 /* Write Keyboard Report Data */
377 Endpoint_Write_Stream_LE(&KeyboardReportData
, sizeof(KeyboardReportData
));
379 /* Finalize the stream transfer to send the last packet */
384 /** Reads the next LED status report from the host from the LED data endpoint, if one has been sent. */
385 void ReceiveNextReport(void)
387 /* Select the Keyboard LED Report Endpoint */
388 Endpoint_SelectEndpoint(KEYBOARD_LEDS_EPNUM
);
390 /* Check if Keyboard LED Endpoint contains a packet */
391 if (Endpoint_IsOUTReceived())
393 /* Check to see if the packet contains data */
394 if (Endpoint_IsReadWriteAllowed())
396 /* Read in the LED report from the host */
397 uint8_t LEDReport
= Endpoint_Read_Byte();
399 /* Process the read LED report from the host */
400 ProcessLEDReport(LEDReport
);
403 /* Handshake the OUT Endpoint - clear endpoint and ready for next report */
408 /** Function to manage status updates to the user. This is done via LEDs on the given board, if available, but may be changed to
409 * log to a serial port, or anything else that is suitable for status updates.
411 * \param CurrentStatus Current status of the system, from the Keyboard_StatusCodes_t enum
413 void UpdateStatus(uint8_t CurrentStatus
)
415 uint8_t LEDMask
= LEDS_NO_LEDS
;
417 /* Set the LED mask to the appropriate LED mask based on the given status code */
418 switch (CurrentStatus
)
420 case Status_USBNotReady
:
421 LEDMask
= (LEDS_LED1
);
423 case Status_USBEnumerating
:
424 LEDMask
= (LEDS_LED1
| LEDS_LED2
);
426 case Status_USBReady
:
427 LEDMask
= (LEDS_LED2
| LEDS_LED4
);
431 /* Set the board LEDs to the new LED mask */
432 LEDs_SetAllLEDs(LEDMask
);
435 /** Function to manage HID report generation and transmission to the host, when in report mode. */
436 TASK(USB_Keyboard_Report
)
438 /* Check if the USB system is connected to a host */
441 /* Send the next keypress report to the host */
444 /* Process the LED report sent from the host */
449 #if defined(INTERRUPT_CONTROL_ENDPOINT)
450 /** ISR for the general Pipe/Endpoint interrupt vector. This ISR fires when an endpoint's status changes (such as
451 * a packet has been received) on an endpoint with its corresponding ISR enabling bits set. This is used to send
452 * HID packets to the host each time the HID interrupt endpoints polling period elapses, as managed by the USB
453 * controller. It is also used to respond to standard and class specific requests send to the device on the control
454 * endpoint, by handing them off to the LUFA library when they are received.
456 ISR(ENDPOINT_PIPE_vect
, ISR_BLOCK
)
458 /* Save previously selected endpoint before selecting a new endpoint */
459 uint8_t PrevSelectedEndpoint
= Endpoint_GetCurrentEndpoint();
461 /* Check if the control endpoint has received a request */
462 if (Endpoint_HasEndpointInterrupted(ENDPOINT_CONTROLEP
))
464 /* Process the control request */
467 /* Handshake the endpoint setup interrupt - must be after the call to USB_USBTask() */
468 USB_INT_Clear(ENDPOINT_INT_SETUP
);
471 /* Restore previously selected endpoint */
472 Endpoint_SelectEndpoint(PrevSelectedEndpoint
);