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 /* 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 { Task
: USB_USBTask
, TaskStatus
: TASK_STOP
},
50 { Task
: USB_Keyboard_Report
, TaskStatus
: TASK_STOP
},
53 /* Global Variables */
54 /** Indicates what report mode the host has requested, true for normal HID reporting mode, false for special boot
55 * protocol reporting mode.
57 bool UsingReportProtocol
= true;
59 /** Current Idle period. This is set by the host via a Set Idle HID class request to silence the device's reports
60 * for either the entire idle duration, or until the report status changes (e.g. the user moves the mouse).
62 uint8_t IdleCount
= 0;
64 /** Current Idle period remaining. When the IdleCount value is set, this tracks the remaining number of idle
65 * milliseconds. This is seperate to the IdleCount timer and is incremented and compared as the host may request
66 * the current idle period via a Get Idle HID class request, thus its value must be preserved.
68 uint16_t IdleMSRemaining
= 0;
71 /** Main program entry point. This routine configures the hardware required by the application, then
72 * starts the scheduler to run the application tasks.
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 */
87 /* Millisecond timer initialization, with output compare interrupt enabled for the idle timing */
89 TCCR0A
= (1 << WGM01
);
90 TCCR0B
= ((1 << CS01
) | (1 << CS00
));
91 TIMSK0
= (1 << OCIE0A
);
93 /* Indicate USB not ready */
94 UpdateStatus(Status_USBNotReady
);
96 /* Initialize Scheduler so that it can be used */
99 /* Initialize USB Subsystem */
102 /* Scheduling - routine never returns, so put this last in the main function */
106 /** Event handler for the USB_Connect event. This indicates that the device is enumerating via the status LEDs and
107 * starts the library USB task to begin the enumeration and USB management process.
109 EVENT_HANDLER(USB_Connect
)
111 /* Start USB management task */
112 Scheduler_SetTaskMode(USB_USBTask
, TASK_RUN
);
114 /* Indicate USB enumerating */
115 UpdateStatus(Status_USBEnumerating
);
118 /** Event handler for the USB_Disconnect event. This indicates that the device is no longer connected to a host via
119 * the status LEDs and stops the USB management and Keyboard reporting tasks.
121 EVENT_HANDLER(USB_Disconnect
)
123 /* Stop running keyboard reporting and USB management tasks */
124 Scheduler_SetTaskMode(USB_Keyboard_Report
, TASK_STOP
);
125 Scheduler_SetTaskMode(USB_USBTask
, TASK_STOP
);
127 /* Indicate USB not ready */
128 UpdateStatus(Status_USBNotReady
);
131 /** Event handler for the USB_ConfigurationChanged event. This is fired when the host set the current configuration
132 * of the USB device after enumeration - the device endpoints are configured and the keyboard reporting task started.
134 EVENT_HANDLER(USB_ConfigurationChanged
)
136 /* Setup Keyboard Keycode Report Endpoint */
137 Endpoint_ConfigureEndpoint(KEYBOARD_EPNUM
, EP_TYPE_INTERRUPT
,
138 ENDPOINT_DIR_IN
, KEYBOARD_EPSIZE
,
139 ENDPOINT_BANK_SINGLE
);
141 /* Setup Keyboard LED Report Endpoint */
142 Endpoint_ConfigureEndpoint(KEYBOARD_LEDS_EPNUM
, EP_TYPE_INTERRUPT
,
143 ENDPOINT_DIR_OUT
, KEYBOARD_EPSIZE
,
144 ENDPOINT_BANK_SINGLE
);
146 /* Indicate USB connected and ready */
147 UpdateStatus(Status_USBReady
);
149 /* Default to report protocol on connect */
150 UsingReportProtocol
= true;
152 /* Start Keyboard reporting task */
153 Scheduler_SetTaskMode(USB_Keyboard_Report
, TASK_RUN
);
156 /** Event handler for the USB_UnhandledControlPacket event. This is used to catch standard and class specific
157 * control requests that are not handled internally by the USB library (including the HID commands, which are
158 * all issued via the control endpoint), so that they can be handled appropriately for the application.
160 EVENT_HANDLER(USB_UnhandledControlPacket
)
162 /* Handle HID Class specific requests */
166 if (bmRequestType
== (REQDIR_DEVICETOHOST
| REQTYPE_CLASS
| REQREC_INTERFACE
))
168 USB_KeyboardReport_Data_t KeyboardReportData
;
170 /* Create the next keyboard report for transmission to the host */
171 GetNextReport(&KeyboardReportData
);
173 /* Ignore report type and ID number value */
174 Endpoint_Discard_Word();
176 /* Ignore unused Interface number value */
177 Endpoint_Discard_Word();
179 /* Read in the number of bytes in the report to send to the host */
180 uint16_t wLength
= Endpoint_Read_Word_LE();
182 /* If trying to send more bytes than exist to the host, clamp the value at the report size */
183 if (wLength
> sizeof(KeyboardReportData
))
184 wLength
= sizeof(KeyboardReportData
);
186 Endpoint_ClearSetupReceived();
188 /* Write the report data to the control endpoint */
189 Endpoint_Write_Control_Stream_LE(&KeyboardReportData
, wLength
);
191 /* Finalize the stream transfer to send the last packet or clear the host abort */
192 Endpoint_ClearSetupOUT();
197 if (bmRequestType
== (REQDIR_HOSTTODEVICE
| REQTYPE_CLASS
| REQREC_INTERFACE
))
199 Endpoint_ClearSetupReceived();
201 /* Wait until the LED report has been sent by the host */
202 while (!(Endpoint_IsSetupOUTReceived()));
204 /* Read in the LED report from the host */
205 uint8_t LEDStatus
= Endpoint_Read_Byte();
207 /* Process the incomming LED report */
208 ProcessLEDReport(LEDStatus
);
210 /* Clear the endpoint data */
211 Endpoint_ClearSetupOUT();
213 /* Wait until the host is ready to receive the request confirmation */
214 while (!(Endpoint_IsSetupINReady()));
216 /* Handshake the request by sending an empty IN packet */
217 Endpoint_ClearSetupIN();
221 case REQ_GetProtocol
:
222 if (bmRequestType
== (REQDIR_DEVICETOHOST
| REQTYPE_CLASS
| REQREC_INTERFACE
))
224 Endpoint_ClearSetupReceived();
226 /* Write the current protocol flag to the host */
227 Endpoint_Write_Byte(UsingReportProtocol
);
229 /* Send the flag to the host */
230 Endpoint_ClearSetupIN();
234 case REQ_SetProtocol
:
235 if (bmRequestType
== (REQDIR_HOSTTODEVICE
| REQTYPE_CLASS
| REQREC_INTERFACE
))
237 /* Read in the wValue parameter containing the new protocol mode */
238 uint16_t wValue
= Endpoint_Read_Word_LE();
240 Endpoint_ClearSetupReceived();
242 /* Set or clear the flag depending on what the host indicates that the current Protocol should be */
243 UsingReportProtocol
= (wValue
!= 0x0000);
245 /* Send an empty packet to acknowedge the command */
246 Endpoint_ClearSetupIN();
251 if (bmRequestType
== (REQDIR_HOSTTODEVICE
| REQTYPE_CLASS
| REQREC_INTERFACE
))
253 /* Read in the wValue parameter containing the idle period */
254 uint16_t wValue
= Endpoint_Read_Word_LE();
256 Endpoint_ClearSetupReceived();
258 /* Get idle period in MSB */
259 IdleCount
= (wValue
>> 8);
261 /* Send an empty packet to acknowedge the command */
262 Endpoint_ClearSetupIN();
267 if (bmRequestType
== (REQDIR_DEVICETOHOST
| REQTYPE_CLASS
| REQREC_INTERFACE
))
269 Endpoint_ClearSetupReceived();
271 /* Write the current idle duration to the host */
272 Endpoint_Write_Byte(IdleCount
);
274 /* Send the flag to the host */
275 Endpoint_ClearSetupIN();
282 /** ISR for the timer 0 compare vector. This ISR fires once each millisecond, and increments the
283 * scheduler elapsed idle period counter when the host has set an idle period.
285 ISR(TIMER0_COMPA_vect
, ISR_BLOCK
)
287 /* One millisecond has elapsed, decrement the idle time remaining counter if it has not already elapsed */
292 /** Fills the given HID report data structure with the next HID report to send to the host.
294 * \param ReportData Pointer to a HID report data structure to be filled
296 * \return Boolean true if the new report differs from the last report, false otherwise
298 bool GetNextReport(USB_KeyboardReport_Data_t
* ReportData
)
300 static uint8_t PrevJoyStatus
= 0;
301 uint8_t JoyStatus_LCL
= Joystick_GetStatus();
302 bool InputChanged
= false;
304 /* Clear the report contents */
305 memset(ReportData
, 0, sizeof(USB_KeyboardReport_Data_t
));
307 if (JoyStatus_LCL
& JOY_UP
)
308 ReportData
->KeyCode
[0] = 0x04; // A
309 else if (JoyStatus_LCL
& JOY_DOWN
)
310 ReportData
->KeyCode
[0] = 0x05; // B
312 if (JoyStatus_LCL
& JOY_LEFT
)
313 ReportData
->KeyCode
[0] = 0x06; // C
314 else if (JoyStatus_LCL
& JOY_RIGHT
)
315 ReportData
->KeyCode
[0] = 0x07; // D
317 if (JoyStatus_LCL
& JOY_PRESS
)
318 ReportData
->KeyCode
[0] = 0x08; // E
320 /* Check if the new report is different to the previous report */
321 InputChanged
= (uint8_t)(PrevJoyStatus
^ JoyStatus_LCL
);
323 /* Save the current joystick status for later comparison */
324 PrevJoyStatus
= JoyStatus_LCL
;
326 /* Return whether the new report is different to the previous report or not */
330 /** Processes a given LED report mask from the host and sets the board LEDs to match.
332 * \param LEDReport LED mask from the host, containing a mask of what LEDs are set
334 void ProcessLEDReport(uint8_t LEDReport
)
336 uint8_t LEDMask
= LEDS_LED2
;
338 if (LEDReport
& 0x01) // NUM Lock
339 LEDMask
|= LEDS_LED1
;
341 if (LEDReport
& 0x02) // CAPS Lock
342 LEDMask
|= LEDS_LED3
;
344 if (LEDReport
& 0x04) // SCROLL Lock
345 LEDMask
|= LEDS_LED4
;
347 /* Set the status LEDs to the current Keyboard LED status */
348 LEDs_SetAllLEDs(LEDMask
);
351 /** Function to manage status updates to the user. This is done via LEDs on the given board, if available, but may be changed to
352 * log to a serial port, or anything else that is suitable for status updates.
354 * \param CurrentStatus Current status of the system, from the Keyboard_StatusCodes_t enum
356 void UpdateStatus(uint8_t CurrentStatus
)
358 uint8_t LEDMask
= LEDS_NO_LEDS
;
360 /* Set the LED mask to the appropriate LED mask based on the given status code */
361 switch (CurrentStatus
)
363 case Status_USBNotReady
:
364 LEDMask
= (LEDS_LED1
);
366 case Status_USBEnumerating
:
367 LEDMask
= (LEDS_LED1
| LEDS_LED2
);
369 case Status_USBReady
:
370 LEDMask
= (LEDS_LED2
| LEDS_LED4
);
374 /* Set the board LEDs to the new LED mask */
375 LEDs_SetAllLEDs(LEDMask
);
378 /** Function to manage HID report generation and transmission to the host, when in report mode. */
379 TASK(USB_Keyboard_Report
)
381 USB_KeyboardReport_Data_t KeyboardReportData
;
384 /* Create the next keyboard report for transmission to the host */
385 SendReport
= GetNextReport(&KeyboardReportData
);
387 /* Check if the idle period is set and has elapsed */
388 if (IdleCount
&& !(IdleMSRemaining
))
390 /* Idle period elapsed, indicate that a report must be sent */
393 /* Reset the idle time remaining counter, must multiply by 4 to get the duration in milliseconds */
394 IdleMSRemaining
= (IdleCount
<< 2);
397 /* Check if the USB system is connected to a host */
400 /* Select the Keyboard Report Endpoint */
401 Endpoint_SelectEndpoint(KEYBOARD_EPNUM
);
403 /* Check if Keyboard Endpoint Ready for Read/Write, and if we should send a report */
404 if (Endpoint_ReadWriteAllowed() && SendReport
)
406 /* Write Keyboard Report Data */
407 Endpoint_Write_Stream_LE(&KeyboardReportData
, sizeof(KeyboardReportData
));
409 /* Finalize the stream transfer to send the last packet */
410 Endpoint_ClearCurrentBank();
413 /* Select the Keyboard LED Report Endpoint */
414 Endpoint_SelectEndpoint(KEYBOARD_LEDS_EPNUM
);
416 /* Check if Keyboard LED Endpoint Ready for Read/Write */
417 if (Endpoint_ReadWriteAllowed())
419 /* Read in the LED report from the host */
420 uint8_t LEDStatus
= Endpoint_Read_Byte();
422 /* Process the incomming LED report */
423 ProcessLEDReport(LEDStatus
);
425 /* Handshake the OUT Endpoint - clear endpoint and ready for next report */
426 Endpoint_ClearCurrentBank();