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 /* Project Tags, for reading out using the ButtLoad project */
40 BUTTLOADTAG(ProjName
, "LUFA Mouse App");
41 BUTTLOADTAG(BuildTime
, __TIME__
);
42 BUTTLOADTAG(BuildDate
, __DATE__
);
43 BUTTLOADTAG(LUFAVersion
, "LUFA V" LUFA_VERSION_STRING
);
45 /* Scheduler Task List */
48 #if !defined(INTERRUPT_CONTROL_ENDPOINT)
49 { Task
: USB_USBTask
, TaskStatus
: TASK_STOP
},
52 #if !defined(INTERRUPT_DATA_ENDPOINT)
53 { Task
: USB_Mouse_Report
, TaskStatus
: TASK_STOP
},
57 /* Global Variables */
58 /** Indicates what report mode the host has requested, true for normal HID reporting mode, false for special boot
59 * protocol reporting mode.
61 bool UsingReportProtocol
= true;
63 /** Current Idle period. This is set by the host via a Set Idle HID class request to silence the device's reports
64 * for either the entire idle duration, or until the report status changes (e.g. the user moves the mouse).
66 uint8_t IdleCount
= 0;
68 /** Current Idle period remaining. When the IdleCount value is set, this tracks the remaining number of idle
69 * milliseconds. This is separate to the IdleCount timer and is incremented and compared as the host may request
70 * the current idle period via a Get Idle HID class request, thus its value must be preserved.
72 uint16_t IdleMSRemaining
= 0;
75 /** Main program entry point. This routine configures the hardware required by the application, then
76 * starts the scheduler to run the application tasks.
80 /* Disable watchdog if enabled by bootloader/fuses */
81 MCUSR
&= ~(1 << WDRF
);
84 /* Disable clock division */
85 clock_prescale_set(clock_div_1
);
87 /* 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 #if !defined(INTERRUPT_CONTROL_ENDPOINT)
117 /* Start USB management task */
118 Scheduler_SetTaskMode(USB_USBTask
, TASK_RUN
);
121 /* Indicate USB enumerating */
122 UpdateStatus(Status_USBEnumerating
);
124 /* Default to report protocol on connect */
125 UsingReportProtocol
= true;
128 /** Event handler for the USB_Reset event. This fires when the USB interface is reset by the USB host, before the
129 * enumeration process begins, and enables the control endpoint interrupt so that control requests can be handled
130 * asynchronously when they arrive rather than when the control endpoint is polled manually.
132 EVENT_HANDLER(USB_Reset
)
134 #if defined(INTERRUPT_CONTROL_ENDPOINT)
135 /* Select the control endpoint */
136 Endpoint_SelectEndpoint(ENDPOINT_CONTROLEP
);
138 /* Enable the endpoint SETUP interrupt ISR for the control endpoint */
139 USB_INT_Enable(ENDPOINT_INT_SETUP
);
143 /** Event handler for the USB_Disconnect event. This indicates that the device is no longer connected to a host via
144 * the status LEDs and stops the USB management and Mouse reporting tasks.
146 EVENT_HANDLER(USB_Disconnect
)
148 /* Stop running keyboard reporting and USB management tasks */
149 #if !defined(INTERRUPT_DATA_ENDPOINT)
150 Scheduler_SetTaskMode(USB_Mouse_Report
, TASK_STOP
);
153 #if !defined(INTERRUPT_CONTROL_ENDPOINT)
154 Scheduler_SetTaskMode(USB_USBTask
, TASK_STOP
);
157 /* Indicate USB not ready */
158 UpdateStatus(Status_USBNotReady
);
161 /** Event handler for the USB_ConfigurationChanged event. This is fired when the host sets the current configuration
162 * of the USB device after enumeration - the device endpoints are configured and the mouse reporting task started.
164 EVENT_HANDLER(USB_ConfigurationChanged
)
166 /* Setup Mouse Report Endpoint */
167 Endpoint_ConfigureEndpoint(MOUSE_EPNUM
, EP_TYPE_INTERRUPT
,
168 ENDPOINT_DIR_IN
, MOUSE_EPSIZE
,
169 ENDPOINT_BANK_SINGLE
);
171 #if defined(INTERRUPT_DATA_ENDPOINT)
172 /* Enable the endpoint IN interrupt ISR for the report endpoint */
173 USB_INT_Enable(ENDPOINT_INT_IN
);
176 /* Indicate USB connected and ready */
177 UpdateStatus(Status_USBReady
);
179 #if !defined(INTERRUPT_DATA_ENDPOINT)
180 /* Start running mouse reporting task */
181 Scheduler_SetTaskMode(USB_Mouse_Report
, TASK_RUN
);
185 /** Event handler for the USB_UnhandledControlPacket event. This is used to catch standard and class specific
186 * control requests that are not handled internally by the USB library (including the HID commands, which are
187 * all issued via the control endpoint), so that they can be handled appropriately for the application.
189 EVENT_HANDLER(USB_UnhandledControlPacket
)
191 /* Handle HID Class specific requests */
195 if (bmRequestType
== (REQDIR_DEVICETOHOST
| REQTYPE_CLASS
| REQREC_INTERFACE
))
197 USB_MouseReport_Data_t MouseReportData
;
199 /* Create the next mouse report for transmission to the host */
200 CreateMouseReport(&MouseReportData
);
202 /* Ignore report type and ID number value */
203 Endpoint_Discard_Word();
205 /* Ignore unused Interface number value */
206 Endpoint_Discard_Word();
208 /* Read in the number of bytes in the report to send to the host */
209 uint16_t wLength
= Endpoint_Read_Word_LE();
211 /* If trying to send more bytes than exist to the host, clamp the value at the report size */
212 if (wLength
> sizeof(MouseReportData
))
213 wLength
= sizeof(MouseReportData
);
215 Endpoint_ClearSetupReceived();
217 /* Write the report data to the control endpoint */
218 Endpoint_Write_Control_Stream_LE(&MouseReportData
, wLength
);
220 /* Clear the report data afterwards */
221 memset(&MouseReportData
, 0, sizeof(MouseReportData
));
223 /* Finalize the stream transfer to send the last packet or clear the host abort */
224 Endpoint_ClearSetupOUT();
228 case REQ_GetProtocol
:
229 if (bmRequestType
== (REQDIR_DEVICETOHOST
| REQTYPE_CLASS
| REQREC_INTERFACE
))
231 Endpoint_ClearSetupReceived();
233 /* Write the current protocol flag to the host */
234 Endpoint_Write_Byte(UsingReportProtocol
);
236 /* Send the flag to the host */
237 Endpoint_ClearSetupIN();
239 /* Acknowledge status stage */
240 while (!(Endpoint_IsSetupOUTReceived()));
241 Endpoint_ClearSetupOUT();
245 case REQ_SetProtocol
:
246 if (bmRequestType
== (REQDIR_HOSTTODEVICE
| REQTYPE_CLASS
| REQREC_INTERFACE
))
248 /* Read in the wValue parameter containing the new protocol mode */
249 uint16_t wValue
= Endpoint_Read_Word_LE();
251 Endpoint_ClearSetupReceived();
253 /* Set or clear the flag depending on what the host indicates that the current Protocol should be */
254 UsingReportProtocol
= (wValue
!= 0x0000);
256 /* Acknowledge status stage */
257 while (!(Endpoint_IsSetupINReady()));
258 Endpoint_ClearSetupIN();
263 if (bmRequestType
== (REQDIR_HOSTTODEVICE
| REQTYPE_CLASS
| REQREC_INTERFACE
))
265 /* Read in the wValue parameter containing the idle period */
266 uint16_t wValue
= Endpoint_Read_Word_LE();
268 Endpoint_ClearSetupReceived();
270 /* Get idle period in MSB */
271 IdleCount
= (wValue
>> 8);
273 /* Acknowledge status stage */
274 while (!(Endpoint_IsSetupINReady()));
275 Endpoint_ClearSetupIN();
280 if (bmRequestType
== (REQDIR_DEVICETOHOST
| REQTYPE_CLASS
| REQREC_INTERFACE
))
282 Endpoint_ClearSetupReceived();
284 /* Write the current idle duration to the host */
285 Endpoint_Write_Byte(IdleCount
);
287 /* Send the flag to the host */
288 Endpoint_ClearSetupIN();
290 /* Acknowledge status stage */
291 while (!(Endpoint_IsSetupOUTReceived()));
292 Endpoint_ClearSetupOUT();
299 /** ISR for the timer 0 compare vector. This ISR fires once each millisecond, and increments the
300 * scheduler elapsed idle period counter when the host has set an idle period.
302 ISR(TIMER0_COMPA_vect
, ISR_BLOCK
)
304 /* One millisecond has elapsed, decrement the idle time remaining counter if it has not already elapsed */
309 /** Fills the given HID report data structure with the next HID report to send to the host.
311 * \param ReportData Pointer to a HID report data structure to be filled
313 void CreateMouseReport(USB_MouseReport_Data_t
* ReportData
)
315 uint8_t JoyStatus_LCL
= Joystick_GetStatus();
317 /* Clear the report contents */
318 memset(ReportData
, 0, sizeof(USB_MouseReport_Data_t
));
320 if (JoyStatus_LCL
& JOY_UP
)
322 else if (JoyStatus_LCL
& JOY_DOWN
)
325 if (JoyStatus_LCL
& JOY_RIGHT
)
327 else if (JoyStatus_LCL
& JOY_LEFT
)
330 if (JoyStatus_LCL
& JOY_PRESS
)
331 ReportData
->Button
= (1 << 0);
334 ReportData
->Button
|= (1 << 1);
337 /** Sends the next HID report to the host, via the keyboard data endpoint. */
338 static inline void SendNextReport(void)
340 static USB_MouseReport_Data_t PrevMouseReportData
;
341 USB_MouseReport_Data_t MouseReportData
;
342 bool SendReport
= true;
344 /* Create the next mouse report for transmission to the host */
345 CreateMouseReport(&MouseReportData
);
347 /* Check if the idle period is set*/
350 /* Determine if the idle period has elapsed */
351 if (!(IdleMSRemaining
))
353 /* Reset the idle time remaining counter, must multiply by 4 to get the duration in milliseconds */
354 IdleMSRemaining
= (IdleCount
<< 2);
358 /* Idle period not elapsed, indicate that a report must not be sent unless the report has changed */
359 SendReport
= (memcmp(&PrevMouseReportData
, &MouseReportData
, sizeof(USB_MouseReport_Data_t
)) != 0);
363 /* Save the current report data for later comparison to check for changes */
364 PrevMouseReportData
= MouseReportData
;
366 /* Select the Mouse Report Endpoint */
367 Endpoint_SelectEndpoint(MOUSE_EPNUM
);
369 /* Check if Mouse Endpoint Ready for Read/Write and if we should send a new report */
370 if (Endpoint_ReadWriteAllowed() && SendReport
)
372 /* Write Mouse Report Data */
373 Endpoint_Write_Stream_LE(&MouseReportData
, sizeof(MouseReportData
));
375 /* Finalize the stream transfer to send the last packet */
376 Endpoint_ClearCurrentBank();
380 /** Function to manage status updates to the user. This is done via LEDs on the given board, if available, but may be changed to
381 * log to a serial port, or anything else that is suitable for status updates.
383 * \param CurrentStatus Current status of the system, from the Mouse_StatusCodes_t enum
385 void UpdateStatus(uint8_t CurrentStatus
)
387 uint8_t LEDMask
= LEDS_NO_LEDS
;
389 /* Set the LED mask to the appropriate LED mask based on the given status code */
390 switch (CurrentStatus
)
392 case Status_USBNotReady
:
393 LEDMask
= (LEDS_LED1
);
395 case Status_USBEnumerating
:
396 LEDMask
= (LEDS_LED1
| LEDS_LED2
);
398 case Status_USBReady
:
399 LEDMask
= (LEDS_LED2
| LEDS_LED4
);
403 /* Set the board LEDs to the new LED mask */
404 LEDs_SetAllLEDs(LEDMask
);
407 #if !defined(INTERRUPT_DATA_ENDPOINT)
408 /** Task to manage HID report generation and transmission to the host, when in report mode. */
409 TASK(USB_Mouse_Report
)
411 /* Check if the USB system is connected to a host */
414 /* Send the next mouse report to the host */
420 /** ISR for the general Pipe/Endpoint interrupt vector. This ISR fires when an endpoint's status changes (such as
421 * a packet has been received) on an endpoint with its corresponding ISR enabling bits set. This is used to send
422 * HID packets to the host each time the HID interrupt endpoints polling period elapses, as managed by the USB
423 * controller. It is also used to respond to standard and class specific requests send to the device on the control
424 * endpoint, by handing them off to the LUFA library when they are received.
426 ISR(ENDPOINT_PIPE_vect
, ISR_BLOCK
)
428 #if defined(INTERRUPT_CONTROL_ENDPOINT)
429 /* Check if the control endpoint has received a request */
430 if (Endpoint_HasEndpointInterrupted(ENDPOINT_CONTROLEP
))
432 /* Clear the endpoint interrupt */
433 Endpoint_ClearEndpointInterrupt(ENDPOINT_CONTROLEP
);
435 /* Process the control request */
438 /* Handshake the endpoint setup interrupt - must be after the call to USB_USBTask() */
439 USB_INT_Clear(ENDPOINT_INT_SETUP
);
443 #if defined(INTERRUPT_DATA_ENDPOINT)
444 /* Check if mouse endpoint has interrupted */
445 if (Endpoint_HasEndpointInterrupted(MOUSE_EPNUM
))
447 /* Select the Mouse Report Endpoint */
448 Endpoint_SelectEndpoint(MOUSE_EPNUM
);
450 /* Clear the endpoint IN interrupt flag */
451 USB_INT_Clear(ENDPOINT_INT_IN
);
453 /* Clear the Mouse Report endpoint interrupt and select the endpoint */
454 Endpoint_ClearEndpointInterrupt(MOUSE_EPNUM
);
456 /* Send the next mouse report to the host */