3 Copyright (C) Dean Camera, 2009.
5 dean [at] fourwalledcubicle [dot] com
6 www.fourwalledcubicle.com
10 Copyright 2009 Dean Camera (dean [at] fourwalledcubicle [dot] com)
12 Permission to use, copy, modify, and distribute this software
13 and its documentation for any purpose and without fee is hereby
14 granted, provided that the above copyright notice appear in all
15 copies and that both that the copyright notice and this
16 permission notice and warranty disclaimer appear in supporting
17 documentation, and that the name of the author not be used in
18 advertising or publicity pertaining to distribution of the
19 software without specific, written prior permission.
21 The author disclaim all warranties with regard to this
22 software, including all implied warranties of merchantability
23 and fitness. In no event shall the author be liable for any
24 special, indirect or consequential damages or any damages
25 whatsoever resulting from loss of use, data or profits, whether
26 in an action of contract, negligence or other tortious action,
27 arising out of or in connection with the use or performance of
33 * Main source file for the Mouse demo. This file contains the main tasks of the demo and
34 * is responsible for the initial application hardware configuration.
39 /* Scheduler Task List */
42 #if !defined(INTERRUPT_CONTROL_ENDPOINT)
43 { .Task
= USB_USBTask
, .TaskStatus
= TASK_STOP
},
46 #if !defined(INTERRUPT_DATA_ENDPOINT)
47 { .Task
= USB_Mouse_Report
, .TaskStatus
= TASK_STOP
},
51 /* Global Variables */
52 /** Indicates what report mode the host has requested, true for normal HID reporting mode, false for special boot
53 * protocol reporting mode.
55 bool UsingReportProtocol
= true;
57 /** Current Idle period. This is set by the host via a Set Idle HID class request to silence the device's reports
58 * for either the entire idle duration, or until the report status changes (e.g. the user moves the mouse).
60 uint8_t IdleCount
= 0;
62 /** Current Idle period remaining. When the IdleCount value is set, this tracks the remaining number of idle
63 * milliseconds. This is separate to the IdleCount timer and is incremented and compared as the host may request
64 * the current idle period via a Get Idle HID class request, thus its value must be preserved.
66 uint16_t IdleMSRemaining
= 0;
69 /** Main program entry point. This routine configures the hardware required by the application, then
70 * starts the scheduler to run the application tasks.
74 /* Disable watchdog if enabled by bootloader/fuses */
75 MCUSR
&= ~(1 << WDRF
);
78 /* Disable clock division */
79 clock_prescale_set(clock_div_1
);
81 /* Hardware Initialization */
86 /* Millisecond timer initialization, with output compare interrupt enabled for the idle timing */
88 TCCR0A
= (1 << WGM01
);
89 TCCR0B
= ((1 << CS01
) | (1 << CS00
));
90 TIMSK0
= (1 << OCIE0A
);
92 /* Indicate USB not ready */
93 UpdateStatus(Status_USBNotReady
);
95 /* Initialize Scheduler so that it can be used */
98 /* Initialize USB Subsystem */
101 /* Scheduling - routine never returns, so put this last in the main function */
105 /** Event handler for the USB_Connect event. This indicates that the device is enumerating via the status LEDs and
106 * starts the library USB task to begin the enumeration and USB management process.
108 EVENT_HANDLER(USB_Connect
)
110 #if !defined(INTERRUPT_CONTROL_ENDPOINT)
111 /* Start USB management task */
112 Scheduler_SetTaskMode(USB_USBTask
, TASK_RUN
);
115 /* Indicate USB enumerating */
116 UpdateStatus(Status_USBEnumerating
);
118 /* Default to report protocol on connect */
119 UsingReportProtocol
= true;
122 /** Event handler for the USB_Reset event. This fires when the USB interface is reset by the USB host, before the
123 * enumeration process begins, and enables the control endpoint interrupt so that control requests can be handled
124 * asynchronously when they arrive rather than when the control endpoint is polled manually.
126 EVENT_HANDLER(USB_Reset
)
128 #if defined(INTERRUPT_CONTROL_ENDPOINT)
129 /* Select the control endpoint */
130 Endpoint_SelectEndpoint(ENDPOINT_CONTROLEP
);
132 /* Enable the endpoint SETUP interrupt ISR for the control endpoint */
133 USB_INT_Enable(ENDPOINT_INT_SETUP
);
137 /** Event handler for the USB_Disconnect event. This indicates that the device is no longer connected to a host via
138 * the status LEDs and stops the USB management and Mouse reporting tasks.
140 EVENT_HANDLER(USB_Disconnect
)
142 /* Stop running mouse reporting and USB management tasks */
143 #if !defined(INTERRUPT_DATA_ENDPOINT)
144 Scheduler_SetTaskMode(USB_Mouse_Report
, TASK_STOP
);
147 #if !defined(INTERRUPT_CONTROL_ENDPOINT)
148 Scheduler_SetTaskMode(USB_USBTask
, TASK_STOP
);
151 /* Indicate USB not ready */
152 UpdateStatus(Status_USBNotReady
);
155 /** Event handler for the USB_ConfigurationChanged event. This is fired when the host sets the current configuration
156 * of the USB device after enumeration - the device endpoints are configured and the mouse reporting task started.
158 EVENT_HANDLER(USB_ConfigurationChanged
)
160 /* Setup Mouse Report Endpoint */
161 Endpoint_ConfigureEndpoint(MOUSE_EPNUM
, EP_TYPE_INTERRUPT
,
162 ENDPOINT_DIR_IN
, MOUSE_EPSIZE
,
163 ENDPOINT_BANK_SINGLE
);
165 #if defined(INTERRUPT_DATA_ENDPOINT)
166 /* Enable the endpoint IN interrupt ISR for the report endpoint */
167 USB_INT_Enable(ENDPOINT_INT_IN
);
170 /* Indicate USB connected and ready */
171 UpdateStatus(Status_USBReady
);
173 #if !defined(INTERRUPT_DATA_ENDPOINT)
174 /* Start running mouse reporting task */
175 Scheduler_SetTaskMode(USB_Mouse_Report
, TASK_RUN
);
179 /** Event handler for the USB_UnhandledControlPacket event. This is used to catch standard and class specific
180 * control requests that are not handled internally by the USB library (including the HID commands, which are
181 * all issued via the control endpoint), so that they can be handled appropriately for the application.
183 EVENT_HANDLER(USB_UnhandledControlPacket
)
185 /* Handle HID Class specific requests */
186 switch (USB_ControlRequest
.bRequest
)
189 if (USB_ControlRequest
.bmRequestType
== (REQDIR_DEVICETOHOST
| REQTYPE_CLASS
| REQREC_INTERFACE
))
191 USB_MouseReport_Data_t MouseReportData
;
193 Endpoint_ClearSETUP();
195 /* Create the next mouse report for transmission to the host */
196 CreateMouseReport(&MouseReportData
);
198 /* Write the report data to the control endpoint */
199 Endpoint_Write_Control_Stream_LE(&MouseReportData
, sizeof(MouseReportData
));
201 /* Clear the report data afterwards */
202 memset(&MouseReportData
, 0, sizeof(MouseReportData
));
204 /* Finalize the stream transfer to send the last packet or clear the host abort */
209 case REQ_GetProtocol
:
210 if (USB_ControlRequest
.bmRequestType
== (REQDIR_DEVICETOHOST
| REQTYPE_CLASS
| REQREC_INTERFACE
))
212 Endpoint_ClearSETUP();
214 /* Write the current protocol flag to the host */
215 Endpoint_Write_Byte(UsingReportProtocol
);
217 /* Send the flag to the host */
220 /* Acknowledge status stage */
221 while (!(Endpoint_IsOUTReceived()));
226 case REQ_SetProtocol
:
227 if (USB_ControlRequest
.bmRequestType
== (REQDIR_HOSTTODEVICE
| REQTYPE_CLASS
| REQREC_INTERFACE
))
229 Endpoint_ClearSETUP();
231 /* Set or clear the flag depending on what the host indicates that the current Protocol should be */
232 UsingReportProtocol
= (USB_ControlRequest
.wValue
!= 0x0000);
234 /* Acknowledge status stage */
235 while (!(Endpoint_IsINReady()));
241 if (USB_ControlRequest
.bmRequestType
== (REQDIR_HOSTTODEVICE
| REQTYPE_CLASS
| REQREC_INTERFACE
))
243 Endpoint_ClearSETUP();
245 /* Get idle period in MSB */
246 IdleCount
= (USB_ControlRequest
.wValue
>> 8);
248 /* Acknowledge status stage */
249 while (!(Endpoint_IsINReady()));
255 if (USB_ControlRequest
.bmRequestType
== (REQDIR_DEVICETOHOST
| REQTYPE_CLASS
| REQREC_INTERFACE
))
257 Endpoint_ClearSETUP();
259 /* Write the current idle duration to the host */
260 Endpoint_Write_Byte(IdleCount
);
262 /* Send the flag to the host */
265 /* Acknowledge status stage */
266 while (!(Endpoint_IsOUTReceived()));
274 /** ISR for the timer 0 compare vector. This ISR fires once each millisecond, and increments the
275 * scheduler elapsed idle period counter when the host has set an idle period.
277 ISR(TIMER0_COMPA_vect
, ISR_BLOCK
)
279 /* One millisecond has elapsed, decrement the idle time remaining counter if it has not already elapsed */
284 /** Fills the given HID report data structure with the next HID report to send to the host.
286 * \param ReportData Pointer to a HID report data structure to be filled
288 void CreateMouseReport(USB_MouseReport_Data_t
* ReportData
)
290 uint8_t JoyStatus_LCL
= Joystick_GetStatus();
292 /* Clear the report contents */
293 memset(ReportData
, 0, sizeof(USB_MouseReport_Data_t
));
295 if (JoyStatus_LCL
& JOY_UP
)
297 else if (JoyStatus_LCL
& JOY_DOWN
)
300 if (JoyStatus_LCL
& JOY_RIGHT
)
302 else if (JoyStatus_LCL
& JOY_LEFT
)
305 if (JoyStatus_LCL
& JOY_PRESS
)
306 ReportData
->Button
= (1 << 0);
309 ReportData
->Button
|= (1 << 1);
312 /** Sends the next HID report to the host, via the keyboard data endpoint. */
313 static inline void SendNextReport(void)
315 static USB_MouseReport_Data_t PrevMouseReportData
;
316 USB_MouseReport_Data_t MouseReportData
;
317 bool SendReport
= true;
319 /* Create the next mouse report for transmission to the host */
320 CreateMouseReport(&MouseReportData
);
322 /* Check if the idle period is set*/
325 /* Determine if the idle period has elapsed */
326 if (!(IdleMSRemaining
))
328 /* Reset the idle time remaining counter, must multiply by 4 to get the duration in milliseconds */
329 IdleMSRemaining
= (IdleCount
<< 2);
333 /* Idle period not elapsed, indicate that a report must not be sent unless the report has changed */
334 SendReport
= (memcmp(&PrevMouseReportData
, &MouseReportData
, sizeof(USB_MouseReport_Data_t
)) != 0);
338 /* Save the current report data for later comparison to check for changes */
339 PrevMouseReportData
= MouseReportData
;
341 /* Select the Mouse Report Endpoint */
342 Endpoint_SelectEndpoint(MOUSE_EPNUM
);
344 /* Check if Mouse Endpoint Ready for Read/Write and if we should send a new report */
345 if (Endpoint_IsReadWriteAllowed() && SendReport
)
347 /* Write Mouse Report Data */
348 Endpoint_Write_Stream_LE(&MouseReportData
, sizeof(MouseReportData
));
350 /* Finalize the stream transfer to send the last packet */
355 /** Function to manage status updates to the user. This is done via LEDs on the given board, if available, but may be changed to
356 * log to a serial port, or anything else that is suitable for status updates.
358 * \param CurrentStatus Current status of the system, from the Mouse_StatusCodes_t enum
360 void UpdateStatus(uint8_t CurrentStatus
)
362 uint8_t LEDMask
= LEDS_NO_LEDS
;
364 /* Set the LED mask to the appropriate LED mask based on the given status code */
365 switch (CurrentStatus
)
367 case Status_USBNotReady
:
368 LEDMask
= (LEDS_LED1
);
370 case Status_USBEnumerating
:
371 LEDMask
= (LEDS_LED1
| LEDS_LED2
);
373 case Status_USBReady
:
374 LEDMask
= (LEDS_LED2
| LEDS_LED4
);
378 /* Set the board LEDs to the new LED mask */
379 LEDs_SetAllLEDs(LEDMask
);
382 #if !defined(INTERRUPT_DATA_ENDPOINT)
383 /** Task to manage HID report generation and transmission to the host, when in report mode. */
384 TASK(USB_Mouse_Report
)
386 /* Check if the USB system is connected to a host */
389 /* Send the next mouse report to the host */
395 /** ISR for the general Pipe/Endpoint interrupt vector. This ISR fires when an endpoint's status changes (such as
396 * a packet has been received) on an endpoint with its corresponding ISR enabling bits set. This is used to send
397 * HID packets to the host each time the HID interrupt endpoints polling period elapses, as managed by the USB
398 * controller. It is also used to respond to standard and class specific requests send to the device on the control
399 * endpoint, by handing them off to the LUFA library when they are received.
401 ISR(ENDPOINT_PIPE_vect
, ISR_BLOCK
)
403 #if defined(INTERRUPT_CONTROL_ENDPOINT)
404 /* Check if the control endpoint has received a request */
405 if (Endpoint_HasEndpointInterrupted(ENDPOINT_CONTROLEP
))
407 /* Clear the endpoint interrupt */
408 Endpoint_ClearEndpointInterrupt(ENDPOINT_CONTROLEP
);
410 /* Process the control request */
413 /* Handshake the endpoint setup interrupt - must be after the call to USB_USBTask() */
414 USB_INT_Clear(ENDPOINT_INT_SETUP
);
418 #if defined(INTERRUPT_DATA_ENDPOINT)
419 /* Check if mouse endpoint has interrupted */
420 if (Endpoint_HasEndpointInterrupted(MOUSE_EPNUM
))
422 /* Select the Mouse Report Endpoint */
423 Endpoint_SelectEndpoint(MOUSE_EPNUM
);
425 /* Clear the endpoint IN interrupt flag */
426 USB_INT_Clear(ENDPOINT_INT_IN
);
428 /* Clear the Mouse Report endpoint interrupt and select the endpoint */
429 Endpoint_ClearEndpointInterrupt(MOUSE_EPNUM
);
431 /* Send the next mouse report to the host */