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 KeyboardFullInt demo. This file contains the main tasks of the demo and
35 * is responsible for the initial application hardware configuration.
40 /* Project Tags, for reading out using the ButtLoad project */
41 BUTTLOADTAG(ProjName
, "LUFA Keyboard App");
42 BUTTLOADTAG(BuildTime
, __TIME__
);
43 BUTTLOADTAG(BuildDate
, __DATE__
);
44 BUTTLOADTAG(LUFAVersion
, "LUFA V" LUFA_VERSION_STRING
);
46 /* Scheduler Task List */
49 #if !defined(INTERRUPT_CONTROL_ENDPOINT)
50 { Task
: USB_USBTask
, TaskStatus
: TASK_STOP
},
53 #if !defined(INTERRUPT_DATA_ENDPOINT)
54 { Task
: USB_Keyboard_Report
, TaskStatus
: TASK_STOP
},
58 /* Global Variables */
59 /** Indicates what report mode the host has requested, true for normal HID reporting mode, false for special boot
60 * protocol reporting mode.
62 bool UsingReportProtocol
= true;
64 /** Current Idle period. This is set by the host via a Set Idle HID class request to silence the device's reports
65 * for either the entire idle duration, or until the report status changes (e.g. the user moves the mouse).
67 uint8_t IdleCount
= 0;
69 /** Current Idle period remaining. When the IdleCount value is set, this tracks the remaining number of idle
70 * milliseconds. This is seperate to the IdleCount timer and is incremented and compared as the host may request
71 * the current idle period via a Get Idle HID class request, thus its value must be preserved.
73 uint16_t IdleMSRemaining
= 0;
76 /** Main program entry point. This routine configures the hardware required by the application, then
77 * starts the scheduler to run the USB management task.
81 /* Disable watchdog if enabled by bootloader/fuses */
82 MCUSR
&= ~(1 << WDRF
);
85 /* Disable clock division */
86 clock_prescale_set(clock_div_1
);
88 /* Hardware Initialization */
92 /* Millisecond timer initialization, with output compare interrupt enabled for the idle timing */
94 TCCR0A
= (1 << WGM01
);
95 TCCR0B
= ((1 << CS01
) | (1 << CS00
));
96 TIMSK0
= (1 << OCIE0A
);
98 /* Indicate USB not ready */
99 UpdateStatus(Status_USBNotReady
);
101 /* Initialize Scheduler so that it can be used */
104 /* Initialize USB Subsystem */
107 /* Scheduling - routine never returns, so put this last in the main function */
111 /** Event handler for the USB_Connect event. This indicates that the device is enumerating via the status LEDs and
112 * starts the library USB task to begin the enumeration and USB management process.
114 EVENT_HANDLER(USB_Connect
)
116 /* Indicate USB enumerating */
117 UpdateStatus(Status_USBEnumerating
);
119 /* Default to report protocol on connect */
120 UsingReportProtocol
= true;
123 /** Event handler for the USB_Reset event. This fires when the USB interface is reset by the USB host, before the
124 * enumeration process begins, and enables the control endpoint interrupt so that control requests can be handled
125 * asynchronously when they arrive rather than when the control endpoint is polled manually.
127 EVENT_HANDLER(USB_Reset
)
129 #if defined(INTERRUPT_CONTROL_ENDPOINT)
130 /* Select the control endpoint */
131 Endpoint_SelectEndpoint(ENDPOINT_CONTROLEP
);
133 /* Enable the endpoint SETUP interrupt ISR for the control endpoint */
134 USB_INT_Enable(ENDPOINT_INT_SETUP
);
138 /** Event handler for the USB_Disconnect event. This indicates that the device is no longer connected to a host via
141 EVENT_HANDLER(USB_Disconnect
)
143 /* Indicate USB not ready */
144 UpdateStatus(Status_USBNotReady
);
147 /** Event handler for the USB_ConfigurationChanged event. This is fired when the host sets the current configuration
148 * of the USB device after enumeration, and configures the keyboard device endpoints.
150 EVENT_HANDLER(USB_ConfigurationChanged
)
152 /* Setup Keyboard Keycode Report Endpoint */
153 Endpoint_ConfigureEndpoint(KEYBOARD_EPNUM
, EP_TYPE_INTERRUPT
,
154 ENDPOINT_DIR_IN
, KEYBOARD_EPSIZE
,
155 ENDPOINT_BANK_SINGLE
);
157 #if defined(INTERRUPT_DATA_ENDPOINT)
158 /* Enable the endpoint IN interrupt ISR for the report endpoint */
159 USB_INT_Enable(ENDPOINT_INT_IN
);
162 /* Setup Keyboard LED Report Endpoint */
163 Endpoint_ConfigureEndpoint(KEYBOARD_LEDS_EPNUM
, EP_TYPE_INTERRUPT
,
164 ENDPOINT_DIR_OUT
, KEYBOARD_EPSIZE
,
165 ENDPOINT_BANK_SINGLE
);
167 #if defined(INTERRUPT_DATA_ENDPOINT)
168 /* Enable the endpoint OUT interrupt ISR for the LED report endpoint */
169 USB_INT_Enable(ENDPOINT_INT_OUT
);
172 /* Indicate USB connected and ready */
173 UpdateStatus(Status_USBReady
);
176 /** Event handler for the USB_UnhandledControlPacket event. This is used to catch standard and class specific
177 * control requests that are not handled internally by the USB library (including the HID commands, which are
178 * all issued via the control endpoint), so that they can be handled appropriately for the application.
180 EVENT_HANDLER(USB_UnhandledControlPacket
)
182 /* Handle HID Class specific requests */
186 if (bmRequestType
== (REQDIR_DEVICETOHOST
| REQTYPE_CLASS
| REQREC_INTERFACE
))
188 USB_KeyboardReport_Data_t KeyboardReportData
;
190 /* Create the next keyboard report for transmission to the host */
191 CreateKeyboardReport(&KeyboardReportData
);
193 /* Ignore report type and ID number value */
194 Endpoint_Discard_Word();
196 /* Ignore unused Interface number value */
197 Endpoint_Discard_Word();
199 /* Read in the number of bytes in the report to send to the host */
200 uint16_t wLength
= Endpoint_Read_Word_LE();
202 /* If trying to send more bytes than exist to the host, clamp the value at the report size */
203 if (wLength
> sizeof(KeyboardReportData
))
204 wLength
= sizeof(KeyboardReportData
);
206 Endpoint_ClearSetupReceived();
208 /* Write the report data to the control endpoint */
209 Endpoint_Write_Control_Stream_LE(&KeyboardReportData
, wLength
);
211 /* Finalize the stream transfer to send the last packet or clear the host abort */
212 Endpoint_ClearSetupOUT();
217 if (bmRequestType
== (REQDIR_HOSTTODEVICE
| REQTYPE_CLASS
| REQREC_INTERFACE
))
219 Endpoint_ClearSetupReceived();
221 /* Wait until the LED report has been sent by the host */
222 while (!(Endpoint_IsSetupOUTReceived()));
224 /* Read in the LED report from the host */
225 uint8_t LEDStatus
= Endpoint_Read_Byte();
227 /* Process the incomming LED report */
228 ProcessLEDReport(LEDStatus
);
230 /* Clear the endpoint data */
231 Endpoint_ClearSetupOUT();
233 /* Acknowledge status stage */
234 while (!(Endpoint_IsSetupINReady()));
235 Endpoint_ClearSetupIN();
239 case REQ_GetProtocol
:
240 if (bmRequestType
== (REQDIR_DEVICETOHOST
| REQTYPE_CLASS
| REQREC_INTERFACE
))
242 Endpoint_ClearSetupReceived();
244 /* Write the current protocol flag to the host */
245 Endpoint_Write_Byte(UsingReportProtocol
);
247 /* Send the flag to the host */
248 Endpoint_ClearSetupIN();
250 /* Acknowledge status stage */
251 while (!(Endpoint_IsSetupOUTReceived()));
252 Endpoint_ClearSetupOUT();
256 case REQ_SetProtocol
:
257 if (bmRequestType
== (REQDIR_HOSTTODEVICE
| REQTYPE_CLASS
| REQREC_INTERFACE
))
259 /* Read in the wValue parameter containing the new protocol mode */
260 uint16_t wValue
= Endpoint_Read_Word_LE();
262 Endpoint_ClearSetupReceived();
264 /* Set or clear the flag depending on what the host indicates that the current Protocol should be */
265 UsingReportProtocol
= (wValue
!= 0x0000);
267 /* Acknowledge status stage */
268 while (!(Endpoint_IsSetupINReady()));
269 Endpoint_ClearSetupIN();
274 if (bmRequestType
== (REQDIR_HOSTTODEVICE
| REQTYPE_CLASS
| REQREC_INTERFACE
))
276 /* Read in the wValue parameter containing the idle period */
277 uint16_t wValue
= Endpoint_Read_Word_LE();
279 Endpoint_ClearSetupReceived();
281 /* Get idle period in MSB */
282 IdleCount
= (wValue
>> 8);
284 /* Acknowledge status stage */
285 while (!(Endpoint_IsSetupINReady()));
286 Endpoint_ClearSetupIN();
291 if (bmRequestType
== (REQDIR_DEVICETOHOST
| REQTYPE_CLASS
| REQREC_INTERFACE
))
293 Endpoint_ClearSetupReceived();
295 /* Write the current idle duration to the host */
296 Endpoint_Write_Byte(IdleCount
);
298 /* Send the flag to the host */
299 Endpoint_ClearSetupIN();
301 /* Acknowledge status stage */
302 while (!(Endpoint_IsSetupOUTReceived()));
303 Endpoint_ClearSetupOUT();
310 /** ISR for the timer 0 compare vector. This ISR fires once each millisecond, and increments the
311 * scheduler elapsed idle period counter when the host has set an idle period.
313 ISR(TIMER0_COMPA_vect
, ISR_BLOCK
)
315 /* One millisecond has elapsed, decrement the idle time remaining counter if it has not already elapsed */
320 /** Fills the given HID report data structure with the next HID report to send to the host.
322 * \param ReportData Pointer to a HID report data structure to be filled
324 * \return Boolean true if the new report differs from the last report, false otherwise
326 bool CreateKeyboardReport(USB_KeyboardReport_Data_t
* ReportData
)
328 static uint8_t PrevJoyStatus
= 0;
329 uint8_t JoyStatus_LCL
= Joystick_GetStatus();
330 bool InputChanged
= false;
332 /* Clear the report contents */
333 memset(ReportData
, 0, sizeof(USB_KeyboardReport_Data_t
));
335 if (JoyStatus_LCL
& JOY_UP
)
336 ReportData
->KeyCode
[0] = 0x04; // A
337 else if (JoyStatus_LCL
& JOY_DOWN
)
338 ReportData
->KeyCode
[0] = 0x05; // B
340 if (JoyStatus_LCL
& JOY_LEFT
)
341 ReportData
->KeyCode
[0] = 0x06; // C
342 else if (JoyStatus_LCL
& JOY_RIGHT
)
343 ReportData
->KeyCode
[0] = 0x07; // D
345 if (JoyStatus_LCL
& JOY_PRESS
)
346 ReportData
->KeyCode
[0] = 0x08; // E
348 /* Check if the new report is different to the previous report */
349 InputChanged
= (uint8_t)(PrevJoyStatus
^ JoyStatus_LCL
);
351 /* Save the current joystick status for later comparison */
352 PrevJoyStatus
= JoyStatus_LCL
;
354 /* Return whether the new report is different to the previous report or not */
358 /** Processes a received LED report, and updates the board LEDs states to match.
360 * \param LEDReport LED status report from the host
362 void ProcessLEDReport(uint8_t LEDReport
)
364 uint8_t LEDMask
= LEDS_LED2
;
366 if (LEDReport
& 0x01) // NUM Lock
367 LEDMask
|= LEDS_LED1
;
369 if (LEDReport
& 0x02) // CAPS Lock
370 LEDMask
|= LEDS_LED3
;
372 if (LEDReport
& 0x04) // SCROLL Lock
373 LEDMask
|= LEDS_LED4
;
375 /* Set the status LEDs to the current Keyboard LED status */
376 LEDs_SetAllLEDs(LEDMask
);
379 /** Sends the next HID report to the host, via the keyboard data endpoint. */
380 static inline void SendNextReport(void)
382 USB_KeyboardReport_Data_t KeyboardReportData
;
385 /* Create the next keyboard report for transmission to the host */
386 SendReport
= CreateKeyboardReport(&KeyboardReportData
);
388 /* Check if the idle period is set and has elapsed */
389 if (IdleCount
&& !(IdleMSRemaining
))
391 /* Idle period elapsed, indicate that a report must be sent */
394 /* Reset the idle time remaining counter, must multiply by 4 to get the duration in milliseconds */
395 IdleMSRemaining
= (IdleCount
<< 2);
398 /* Select the Keyboard Report Endpoint */
399 Endpoint_SelectEndpoint(KEYBOARD_EPNUM
);
401 /* Check if Keyboard Endpoint Ready for Read/Write, and if we should send a report */
402 if (Endpoint_ReadWriteAllowed() && SendReport
)
404 /* Write Keyboard Report Data */
405 Endpoint_Write_Stream_LE(&KeyboardReportData
, sizeof(KeyboardReportData
));
407 /* Finalize the stream transfer to send the last packet */
408 Endpoint_ClearCurrentBank();
412 /** Reads the next LED status report from the host from the LED data endpoint, if one has been sent. */
413 static inline void ReceiveNextReport(void)
415 /* Select the Keyboard LED Report Endpoint */
416 Endpoint_SelectEndpoint(KEYBOARD_LEDS_EPNUM
);
418 /* Check if Keyboard LED Endpoint Ready for Read/Write */
419 if (!(Endpoint_ReadWriteAllowed()))
422 /* Read in the LED report from the host */
423 uint8_t LEDReport
= Endpoint_Read_Byte();
425 /* Handshake the OUT Endpoint - clear endpoint and ready for next report */
426 Endpoint_ClearCurrentBank();
428 /* Process the read LED report from the host */
429 ProcessLEDReport(LEDReport
);
432 /** Function to manage status updates to the user. This is done via LEDs on the given board, if available, but may be changed to
433 * log to a serial port, or anything else that is suitable for status updates.
435 * \param CurrentStatus Current status of the system, from the KeyboardFullInt_StatusCodes_t enum
437 void UpdateStatus(uint8_t CurrentStatus
)
439 uint8_t LEDMask
= LEDS_NO_LEDS
;
441 /* Set the LED mask to the appropriate LED mask based on the given status code */
442 switch (CurrentStatus
)
444 case Status_USBNotReady
:
445 LEDMask
= (LEDS_LED1
);
447 case Status_USBEnumerating
:
448 LEDMask
= (LEDS_LED1
| LEDS_LED2
);
450 case Status_USBReady
:
451 LEDMask
= (LEDS_LED2
| LEDS_LED4
);
455 /* Set the board LEDs to the new LED mask */
456 LEDs_SetAllLEDs(LEDMask
);
459 #if !defined(INTERRUPT_DATA_ENDPOINT)
460 /** Function to manage HID report generation and transmission to the host, when in report mode. */
461 TASK(USB_Keyboard_Report
)
463 /* Check if the USB system is connected to a host */
466 /* Send the next keypress report to the host */
469 /* Process the LED report sent from the host */
475 /** ISR for the general Pipe/Endpoint interrupt vector. This ISR fires when an endpoint's status changes (such as
476 * a packet has been received) on an endpoint with its corresponding ISR enabling bits set. This is used to send
477 * HID packets to the host each time the HID interrupt endpoints polling period elapses, as managed by the USB
478 * controller. It is also used to respond to standard and class specific requests send to the device on the control
479 * endpoint, by handing them off to the LUFA library when they are received.
481 ISR(ENDPOINT_PIPE_vect
, ISR_BLOCK
)
483 #if defined(INTERRUPT_CONTROL_ENDPOINT)
484 /* Check if the control endpoint has received a request */
485 if (Endpoint_HasEndpointInterrupted(ENDPOINT_CONTROLEP
))
487 /* Clear the endpoint interrupt */
488 Endpoint_ClearEndpointInterrupt(ENDPOINT_CONTROLEP
);
490 /* Process the control request */
493 /* Handshake the endpoint setup interrupt - must be after the call to USB_USBTask() */
494 USB_INT_Clear(ENDPOINT_INT_SETUP
);
498 #if defined(INTERRUPT_DATA_ENDPOINT)
499 /* Check if keyboard endpoint has interrupted */
500 if (Endpoint_HasEndpointInterrupted(KEYBOARD_EPNUM
))
502 /* Select the Keyboard Report Endpoint */
503 Endpoint_SelectEndpoint(KEYBOARD_EPNUM
);
505 /* Clear the endpoint IN interrupt flag */
506 USB_INT_Clear(ENDPOINT_INT_IN
);
508 /* Clear the Keyboard Report endpoint interrupt */
509 Endpoint_ClearEndpointInterrupt(KEYBOARD_EPNUM
);
511 /* Send the next keypress report to the host */
515 /* Check if Keyboard LED status Endpoint has interrupted */
516 if (Endpoint_HasEndpointInterrupted(KEYBOARD_LEDS_EPNUM
))
518 /* Select the Keyboard LED Report Endpoint */
519 Endpoint_SelectEndpoint(KEYBOARD_LEDS_EPNUM
);
521 /* Clear the endpoint OUT interrupt flag */
522 USB_INT_Clear(ENDPOINT_INT_OUT
);
524 /* Clear the Keyboard LED Report endpoint interrupt */
525 Endpoint_ClearEndpointInterrupt(KEYBOARD_LEDS_EPNUM
);
527 /* Process the LED report sent from the host */