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 { .Task
= USB_USBTask
, .TaskStatus
= TASK_STOP
},
44 { .Task
= USB_Keyboard_Report
, .TaskStatus
= TASK_STOP
},
47 /* Global Variables */
48 /** Indicates what report mode the host has requested, true for normal HID reporting mode, false for special boot
49 * protocol reporting mode.
51 bool UsingReportProtocol
= true;
53 /** Current Idle period. This is set by the host via a Set Idle HID class request to silence the device's reports
54 * for either the entire idle duration, or until the report status changes (e.g. the user presses a key).
56 uint16_t IdleCount
= 500;
58 /** Current Idle period remaining. When the IdleCount value is set, this tracks the remaining number of idle
59 * milliseconds. This is separate to the IdleCount timer and is incremented and compared as the host may request
60 * the current idle period via a Get Idle HID class request, thus its value must be preserved.
62 uint16_t IdleMSRemaining
= 0;
65 /** Main program entry point. This routine configures the hardware required by the application, then
66 * starts the scheduler to run the USB management task.
70 /* Disable watchdog if enabled by bootloader/fuses */
71 MCUSR
&= ~(1 << WDRF
);
74 /* Disable clock division */
75 clock_prescale_set(clock_div_1
);
77 /* Hardware Initialization */
81 /* Millisecond timer initialization, with output compare interrupt enabled for the idle timing */
83 TCCR0A
= (1 << WGM01
);
84 TCCR0B
= ((1 << CS01
) | (1 << CS00
));
85 TIMSK0
= (1 << OCIE0A
);
87 /* Indicate USB not ready */
88 UpdateStatus(Status_USBNotReady
);
90 /* Initialize Scheduler so that it can be used */
93 /* Initialize USB Subsystem */
96 /* Scheduling - routine never returns, so put this last in the main function */
100 /** Event handler for the USB_Connect event. This indicates that the device is enumerating via the status LEDs and
101 * starts the library USB task to begin the enumeration and USB management process.
103 void EVENT_USB_Connect(void)
105 /* Start USB management task */
106 Scheduler_SetTaskMode(USB_USBTask
, TASK_RUN
);
108 /* Indicate USB enumerating */
109 UpdateStatus(Status_USBEnumerating
);
111 /* Default to report protocol on connect */
112 UsingReportProtocol
= true;
115 /** Event handler for the USB_Disconnect event. This indicates that the device is no longer connected to a host via
118 void EVENT_USB_Disconnect(void)
120 /* Stop running keyboard reporting and USB management tasks */
121 Scheduler_SetTaskMode(USB_Keyboard_Report
, TASK_STOP
);
122 Scheduler_SetTaskMode(USB_USBTask
, TASK_STOP
);
124 /* Indicate USB not ready */
125 UpdateStatus(Status_USBNotReady
);
128 /** Event handler for the USB_ConfigurationChanged event. This is fired when the host sets the current configuration
129 * of the USB device after enumeration, and configures the keyboard device endpoints.
131 void EVENT_USB_ConfigurationChanged(void)
133 /* Setup Keyboard Keycode Report Endpoint */
134 Endpoint_ConfigureEndpoint(KEYBOARD_EPNUM
, EP_TYPE_INTERRUPT
,
135 ENDPOINT_DIR_IN
, KEYBOARD_EPSIZE
,
136 ENDPOINT_BANK_SINGLE
);
138 /* Setup Keyboard LED Report Endpoint */
139 Endpoint_ConfigureEndpoint(KEYBOARD_LEDS_EPNUM
, EP_TYPE_INTERRUPT
,
140 ENDPOINT_DIR_OUT
, KEYBOARD_EPSIZE
,
141 ENDPOINT_BANK_SINGLE
);
143 /* Indicate USB connected and ready */
144 UpdateStatus(Status_USBReady
);
146 /* Start running keyboard reporting task */
147 Scheduler_SetTaskMode(USB_Keyboard_Report
, TASK_RUN
);
150 /** Event handler for the USB_UnhandledControlPacket event. This is used to catch standard and class specific
151 * control requests that are not handled internally by the USB library (including the HID commands, which are
152 * all issued via the control endpoint), so that they can be handled appropriately for the application.
154 void EVENT_USB_UnhandledControlPacket(void)
156 /* Handle HID Class specific requests */
157 switch (USB_ControlRequest
.bRequest
)
160 if (USB_ControlRequest
.bmRequestType
== (REQDIR_DEVICETOHOST
| REQTYPE_CLASS
| REQREC_INTERFACE
))
162 USB_KeyboardReport_Data_t KeyboardReportData
;
164 Endpoint_ClearSETUP();
166 /* Create the next keyboard report for transmission to the host */
167 CreateKeyboardReport(&KeyboardReportData
);
169 /* Write the report data to the control endpoint */
170 Endpoint_Write_Control_Stream_LE(&KeyboardReportData
, sizeof(KeyboardReportData
));
172 /* Finalize the stream transfer to send the last packet or clear the host abort */
178 if (USB_ControlRequest
.bmRequestType
== (REQDIR_HOSTTODEVICE
| REQTYPE_CLASS
| REQREC_INTERFACE
))
180 Endpoint_ClearSETUP();
182 /* Wait until the LED report has been sent by the host */
183 while (!(Endpoint_IsOUTReceived()));
185 /* Read in the LED report from the host */
186 uint8_t LEDStatus
= Endpoint_Read_Byte();
188 /* Process the incoming LED report */
189 ProcessLEDReport(LEDStatus
);
191 /* Clear the endpoint data */
194 /* Acknowledge status stage */
195 while (!(Endpoint_IsINReady()));
200 case REQ_GetProtocol
:
201 if (USB_ControlRequest
.bmRequestType
== (REQDIR_DEVICETOHOST
| REQTYPE_CLASS
| REQREC_INTERFACE
))
203 Endpoint_ClearSETUP();
205 /* Write the current protocol flag to the host */
206 Endpoint_Write_Byte(UsingReportProtocol
);
208 /* Send the flag to the host */
211 /* Acknowledge status stage */
212 while (!(Endpoint_IsOUTReceived()));
217 case REQ_SetProtocol
:
218 if (USB_ControlRequest
.bmRequestType
== (REQDIR_HOSTTODEVICE
| REQTYPE_CLASS
| REQREC_INTERFACE
))
220 Endpoint_ClearSETUP();
222 /* Set or clear the flag depending on what the host indicates that the current Protocol should be */
223 UsingReportProtocol
= (USB_ControlRequest
.wValue
!= 0);
225 /* Acknowledge status stage */
226 while (!(Endpoint_IsINReady()));
232 if (USB_ControlRequest
.bmRequestType
== (REQDIR_HOSTTODEVICE
| REQTYPE_CLASS
| REQREC_INTERFACE
))
234 Endpoint_ClearSETUP();
236 /* Get idle period in MSB */
237 IdleCount
= (USB_ControlRequest
.wValue
>> 8);
239 /* Acknowledge status stage */
240 while (!(Endpoint_IsINReady()));
246 if (USB_ControlRequest
.bmRequestType
== (REQDIR_DEVICETOHOST
| REQTYPE_CLASS
| REQREC_INTERFACE
))
248 Endpoint_ClearSETUP();
250 /* Write the current idle duration to the host */
251 Endpoint_Write_Byte(IdleCount
);
253 /* Send the flag to the host */
256 /* Acknowledge status stage */
257 while (!(Endpoint_IsOUTReceived()));
265 /** ISR for the timer 0 compare vector. This ISR fires once each millisecond, and increments the
266 * scheduler elapsed idle period counter when the host has set an idle period.
268 ISR(TIMER0_COMPA_vect
, ISR_BLOCK
)
270 /* One millisecond has elapsed, decrement the idle time remaining counter if it has not already elapsed */
275 /** Fills the given HID report data structure with the next HID report to send to the host.
277 * \param ReportData Pointer to a HID report data structure to be filled
279 void CreateKeyboardReport(USB_KeyboardReport_Data_t
* ReportData
)
281 uint8_t JoyStatus_LCL
= Joystick_GetStatus();
283 /* Clear the report contents */
284 memset(ReportData
, 0, sizeof(USB_KeyboardReport_Data_t
));
286 if (JoyStatus_LCL
& JOY_UP
)
287 ReportData
->KeyCode
[0] = 0x04; // A
288 else if (JoyStatus_LCL
& JOY_DOWN
)
289 ReportData
->KeyCode
[0] = 0x05; // B
291 if (JoyStatus_LCL
& JOY_LEFT
)
292 ReportData
->KeyCode
[0] = 0x06; // C
293 else if (JoyStatus_LCL
& JOY_RIGHT
)
294 ReportData
->KeyCode
[0] = 0x07; // D
296 if (JoyStatus_LCL
& JOY_PRESS
)
297 ReportData
->KeyCode
[0] = 0x08; // E
300 /** Processes a received LED report, and updates the board LEDs states to match.
302 * \param LEDReport LED status report from the host
304 void ProcessLEDReport(uint8_t LEDReport
)
306 uint8_t LEDMask
= LEDS_LED2
;
308 if (LEDReport
& 0x01) // NUM Lock
309 LEDMask
|= LEDS_LED1
;
311 if (LEDReport
& 0x02) // CAPS Lock
312 LEDMask
|= LEDS_LED3
;
314 if (LEDReport
& 0x04) // SCROLL Lock
315 LEDMask
|= LEDS_LED4
;
317 /* Set the status LEDs to the current Keyboard LED status */
318 LEDs_SetAllLEDs(LEDMask
);
321 /** Sends the next HID report to the host, via the keyboard data endpoint. */
322 void SendNextReport(void)
324 static USB_KeyboardReport_Data_t PrevKeyboardReportData
;
325 USB_KeyboardReport_Data_t KeyboardReportData
;
326 bool SendReport
= true;
328 /* Create the next keyboard report for transmission to the host */
329 CreateKeyboardReport(&KeyboardReportData
);
331 /* Check to see if the report data has changed - if so a report MUST be sent */
332 SendReport
= (memcmp(&PrevKeyboardReportData
, &KeyboardReportData
, sizeof(USB_KeyboardReport_Data_t
)) != 0);
334 /* Save the current report data for later comparison to check for changes */
335 PrevKeyboardReportData
= KeyboardReportData
;
337 /* Check if the idle period is set and has elapsed */
338 if ((IdleCount
!= HID_IDLE_CHANGESONLY
) && (!(IdleMSRemaining
)))
340 /* Reset the idle time remaining counter, must multiply by 4 to get the duration in milliseconds */
341 IdleMSRemaining
= (IdleCount
<< 2);
343 /* Idle period is set and has elapsed, must send a report to the host */
347 /* Select the Keyboard Report Endpoint */
348 Endpoint_SelectEndpoint(KEYBOARD_EPNUM
);
350 /* Check if Keyboard Endpoint Ready for Read/Write and if we should send a new report */
351 if (Endpoint_IsReadWriteAllowed() && SendReport
)
353 /* Write Keyboard Report Data */
354 Endpoint_Write_Stream_LE(&KeyboardReportData
, sizeof(KeyboardReportData
));
356 /* Finalize the stream transfer to send the last packet */
361 /** Reads the next LED status report from the host from the LED data endpoint, if one has been sent. */
362 void ReceiveNextReport(void)
364 /* Select the Keyboard LED Report Endpoint */
365 Endpoint_SelectEndpoint(KEYBOARD_LEDS_EPNUM
);
367 /* Check if Keyboard LED Endpoint contains a packet */
368 if (Endpoint_IsOUTReceived())
370 /* Check to see if the packet contains data */
371 if (Endpoint_IsReadWriteAllowed())
373 /* Read in the LED report from the host */
374 uint8_t LEDReport
= Endpoint_Read_Byte();
376 /* Process the read LED report from the host */
377 ProcessLEDReport(LEDReport
);
380 /* Handshake the OUT Endpoint - clear endpoint and ready for next report */
385 /** Function to manage status updates to the user. This is done via LEDs on the given board, if available, but may be changed to
386 * log to a serial port, or anything else that is suitable for status updates.
388 * \param CurrentStatus Current status of the system, from the Keyboard_StatusCodes_t enum
390 void UpdateStatus(uint8_t CurrentStatus
)
392 uint8_t LEDMask
= LEDS_NO_LEDS
;
394 /* Set the LED mask to the appropriate LED mask based on the given status code */
395 switch (CurrentStatus
)
397 case Status_USBNotReady
:
398 LEDMask
= (LEDS_LED1
);
400 case Status_USBEnumerating
:
401 LEDMask
= (LEDS_LED1
| LEDS_LED2
);
403 case Status_USBReady
:
404 LEDMask
= (LEDS_LED2
| LEDS_LED4
);
408 /* Set the board LEDs to the new LED mask */
409 LEDs_SetAllLEDs(LEDMask
);
412 /** Function to manage HID report generation and transmission to the host, when in report mode. */
413 TASK(USB_Keyboard_Report
)
415 /* Check if the USB system is connected to a host */
418 /* Send the next keypress report to the host */
421 /* Process the LED report sent from the host */