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 { .Task
= USB_USBTask
, .TaskStatus
= TASK_STOP
},
43 { .Task
= USB_Mouse_Report
, .TaskStatus
= TASK_STOP
},
46 /* Global Variables */
47 /** Indicates what report mode the host has requested, true for normal HID reporting mode, false for special boot
48 * protocol reporting mode.
50 bool UsingReportProtocol
= true;
52 /** Current Idle period. This is set by the host via a Set Idle HID class request to silence the device's reports
53 * for either the entire idle duration, or until the report status changes (e.g. the user moves the mouse).
55 uint16_t IdleCount
= HID_IDLE_CHANGESONLY
;
57 /** Current Idle period remaining. When the IdleCount value is set, this tracks the remaining number of idle
58 * milliseconds. This is separate to the IdleCount timer and is incremented and compared as the host may request
59 * the current idle period via a Get Idle HID class request, thus its value must be preserved.
61 uint16_t IdleMSRemaining
= 0;
64 /** Main program entry point. This routine configures the hardware required by the application, then
65 * starts the scheduler to run the application tasks.
69 /* Disable watchdog if enabled by bootloader/fuses */
70 MCUSR
&= ~(1 << WDRF
);
73 /* Disable clock division */
74 clock_prescale_set(clock_div_1
);
76 /* 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
116 * the status LEDs and stops the USB management and Mouse reporting tasks.
118 void EVENT_USB_Disconnect(void)
120 /* Stop running mouse reporting and USB management tasks */
121 Scheduler_SetTaskMode(USB_Mouse_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 - the device endpoints are configured and the mouse reporting task started.
131 void EVENT_USB_ConfigurationChanged(void)
133 /* Setup Mouse Report Endpoint */
134 Endpoint_ConfigureEndpoint(MOUSE_EPNUM
, EP_TYPE_INTERRUPT
,
135 ENDPOINT_DIR_IN
, MOUSE_EPSIZE
,
136 ENDPOINT_BANK_SINGLE
);
138 /* Indicate USB connected and ready */
139 UpdateStatus(Status_USBReady
);
141 /* Start running mouse reporting task */
142 Scheduler_SetTaskMode(USB_Mouse_Report
, TASK_RUN
);
145 /** Event handler for the USB_UnhandledControlPacket event. This is used to catch standard and class specific
146 * control requests that are not handled internally by the USB library (including the HID commands, which are
147 * all issued via the control endpoint), so that they can be handled appropriately for the application.
149 void EVENT_USB_UnhandledControlPacket(void)
151 /* Handle HID Class specific requests */
152 switch (USB_ControlRequest
.bRequest
)
155 if (USB_ControlRequest
.bmRequestType
== (REQDIR_DEVICETOHOST
| REQTYPE_CLASS
| REQREC_INTERFACE
))
157 USB_MouseReport_Data_t MouseReportData
;
159 Endpoint_ClearSETUP();
161 /* Create the next mouse report for transmission to the host */
162 CreateMouseReport(&MouseReportData
);
164 /* Write the report data to the control endpoint */
165 Endpoint_Write_Control_Stream_LE(&MouseReportData
, sizeof(MouseReportData
));
167 /* Clear the report data afterwards */
168 memset(&MouseReportData
, 0, sizeof(MouseReportData
));
170 /* Finalize the stream transfer to send the last packet or clear the host abort */
175 case REQ_GetProtocol
:
176 if (USB_ControlRequest
.bmRequestType
== (REQDIR_DEVICETOHOST
| REQTYPE_CLASS
| REQREC_INTERFACE
))
178 Endpoint_ClearSETUP();
180 /* Write the current protocol flag to the host */
181 Endpoint_Write_Byte(UsingReportProtocol
);
183 /* Send the flag to the host */
186 /* Acknowledge status stage */
187 while (!(Endpoint_IsOUTReceived()));
192 case REQ_SetProtocol
:
193 if (USB_ControlRequest
.bmRequestType
== (REQDIR_HOSTTODEVICE
| REQTYPE_CLASS
| REQREC_INTERFACE
))
195 Endpoint_ClearSETUP();
197 /* Set or clear the flag depending on what the host indicates that the current Protocol should be */
198 UsingReportProtocol
= (USB_ControlRequest
.wValue
!= 0);
200 /* Acknowledge status stage */
201 while (!(Endpoint_IsINReady()));
207 if (USB_ControlRequest
.bmRequestType
== (REQDIR_HOSTTODEVICE
| REQTYPE_CLASS
| REQREC_INTERFACE
))
209 Endpoint_ClearSETUP();
211 /* Get idle period in MSB */
212 IdleCount
= (USB_ControlRequest
.wValue
>> 8);
214 /* Acknowledge status stage */
215 while (!(Endpoint_IsINReady()));
221 if (USB_ControlRequest
.bmRequestType
== (REQDIR_DEVICETOHOST
| REQTYPE_CLASS
| REQREC_INTERFACE
))
223 Endpoint_ClearSETUP();
225 /* Write the current idle duration to the host */
226 Endpoint_Write_Byte(IdleCount
);
228 /* Send the flag to the host */
231 /* Acknowledge status stage */
232 while (!(Endpoint_IsOUTReceived()));
240 /** ISR for the timer 0 compare vector. This ISR fires once each millisecond, and increments the
241 * scheduler elapsed idle period counter when the host has set an idle period.
243 ISR(TIMER0_COMPA_vect
, ISR_BLOCK
)
245 /* One millisecond has elapsed, decrement the idle time remaining counter if it has not already elapsed */
250 /** Fills the given HID report data structure with the next HID report to send to the host.
252 * \param ReportData Pointer to a HID report data structure to be filled
254 void CreateMouseReport(USB_MouseReport_Data_t
* ReportData
)
256 uint8_t JoyStatus_LCL
= Joystick_GetStatus();
257 uint8_t ButtonStatus_LCL
= Buttons_GetStatus();
259 /* Clear the report contents */
260 memset(ReportData
, 0, sizeof(USB_MouseReport_Data_t
));
262 if (JoyStatus_LCL
& JOY_UP
)
264 else if (JoyStatus_LCL
& JOY_DOWN
)
267 if (JoyStatus_LCL
& JOY_RIGHT
)
269 else if (JoyStatus_LCL
& JOY_LEFT
)
272 if (JoyStatus_LCL
& JOY_PRESS
)
273 ReportData
->Button
= (1 << 0);
275 if (ButtonStatus_LCL
& BUTTONS_BUTTON1
)
276 ReportData
->Button
|= (1 << 1);
279 /** Sends the next HID report to the host, via the keyboard data endpoint. */
280 void SendNextReport(void)
282 static USB_MouseReport_Data_t PrevMouseReportData
;
283 USB_MouseReport_Data_t MouseReportData
;
286 /* Create the next mouse report for transmission to the host */
287 CreateMouseReport(&MouseReportData
);
289 /* Check to see if the report data has changed - if so a report MUST be sent */
290 SendReport
= (memcmp(&PrevMouseReportData
, &MouseReportData
, sizeof(USB_MouseReport_Data_t
)) != 0);
292 /* Override the check if the Y or X values are non-zero - we want continuous movement while the joystick
293 * is being held down (via continuous reports), otherwise the cursor will only move once per joystick toggle */
294 if ((MouseReportData
.Y
!= 0) || (MouseReportData
.X
!= 0))
297 /* Save the current report data for later comparison to check for changes */
298 PrevMouseReportData
= MouseReportData
;
300 /* Check if the idle period is set and has elapsed */
301 if ((IdleCount
!= HID_IDLE_CHANGESONLY
) && (!(IdleMSRemaining
)))
303 /* Reset the idle time remaining counter, must multiply by 4 to get the duration in milliseconds */
304 IdleMSRemaining
= (IdleCount
<< 2);
306 /* Idle period is set and has elapsed, must send a report to the host */
310 /* Select the Mouse Report Endpoint */
311 Endpoint_SelectEndpoint(MOUSE_EPNUM
);
313 /* Check if Mouse Endpoint Ready for Read/Write and if we should send a new report */
314 if (Endpoint_IsReadWriteAllowed() && SendReport
)
316 /* Write Mouse Report Data */
317 Endpoint_Write_Stream_LE(&MouseReportData
, sizeof(MouseReportData
));
319 /* Finalize the stream transfer to send the last packet */
324 /** Function to manage status updates to the user. This is done via LEDs on the given board, if available, but may be changed to
325 * log to a serial port, or anything else that is suitable for status updates.
327 * \param CurrentStatus Current status of the system, from the Mouse_StatusCodes_t enum
329 void UpdateStatus(uint8_t CurrentStatus
)
331 uint8_t LEDMask
= LEDS_NO_LEDS
;
333 /* Set the LED mask to the appropriate LED mask based on the given status code */
334 switch (CurrentStatus
)
336 case Status_USBNotReady
:
337 LEDMask
= (LEDS_LED1
);
339 case Status_USBEnumerating
:
340 LEDMask
= (LEDS_LED1
| LEDS_LED2
);
342 case Status_USBReady
:
343 LEDMask
= (LEDS_LED2
| LEDS_LED4
);
347 /* Set the board LEDs to the new LED mask */
348 LEDs_SetAllLEDs(LEDMask
);
351 /** Task to manage HID report generation and transmission to the host, when in report mode. */
352 TASK(USB_Mouse_Report
)
354 /* Check if the USB system is connected to a host */
357 /* Send the next mouse report to the host */