3 Copyright (C) Dean Camera, 2014.
5 dean [at] fourwalledcubicle [dot] com
10 Copyright 2014 Dean Camera (dean [at] fourwalledcubicle [dot] com)
12 Permission to use, copy, modify, distribute, and sell this
13 software and its documentation for any purpose is hereby granted
14 without fee, provided that the above copyright notice appear in
15 all 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 disclaims 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 /** Indicates what report mode the host has requested, true for normal HID reporting mode, \c false for special boot
40 * protocol reporting mode.
42 static bool UsingReportProtocol = true;
44 /** Current Idle period. This is set by the host via a Set Idle HID class request to silence the device's reports
45 * for either the entire idle duration, or until the report status changes (e.g. the user moves the mouse).
47 static uint16_t IdleCount = 0;
49 /** Current Idle period remaining. When the IdleCount value is set, this tracks the remaining number of idle
50 * milliseconds. This is separate to the IdleCount timer and is incremented and compared as the host may request
51 * the current idle period via a Get Idle HID class request, thus its value must be preserved.
53 static uint16_t IdleMSRemaining = 0;
56 /** Main program entry point. This routine configures the hardware required by the application, then
57 * enters a loop to run the application tasks in sequence.
63 LEDs_SetAllLEDs(LEDMASK_USB_NOTREADY);
64 GlobalInterruptEnable();
73 /** Configures the board hardware and chip peripherals for the demo's functionality. */
74 void SetupHardware(void)
76 #if (ARCH == ARCH_AVR8)
77 /* Disable watchdog if enabled by bootloader/fuses */
78 MCUSR &= ~(1 << WDRF);
81 /* Disable clock division */
82 clock_prescale_set(clock_div_1);
83 #elif (ARCH == ARCH_XMEGA)
84 /* Start the PLL to multiply the 2MHz RC oscillator to 32MHz and switch the CPU core to run from it */
85 XMEGACLK_StartPLL(CLOCK_SRC_INT_RC2MHZ, 2000000, F_CPU);
86 XMEGACLK_SetCPUClockSource(CLOCK_SRC_PLL);
88 /* Start the 32MHz internal RC oscillator and start the DFLL to increase it to 48MHz using the USB SOF as a reference */
89 XMEGACLK_StartInternalOscillator(CLOCK_SRC_INT_RC32MHZ);
90 XMEGACLK_StartDFLL(CLOCK_SRC_INT_RC32MHZ, DFLL_REF_INT_USBSOF, F_USB);
92 PMIC.CTRL = PMIC_LOLVLEN_bm | PMIC_MEDLVLEN_bm | PMIC_HILVLEN_bm;
95 /* Hardware Initialization */
102 /** Event handler for the USB_Connect event. This indicates that the device is enumerating via the status LEDs and
103 * starts the library USB task to begin the enumeration and USB management process.
105 void EVENT_USB_Device_Connect(void)
107 /* Indicate USB enumerating */
108 LEDs_SetAllLEDs(LEDMASK_USB_ENUMERATING);
110 /* Default to report protocol on connect */
111 UsingReportProtocol = true;
114 /** Event handler for the USB_Disconnect event. This indicates that the device is no longer connected to a host via
115 * the status LEDs and stops the USB management and Mouse reporting tasks.
117 void EVENT_USB_Device_Disconnect(void)
119 /* Indicate USB not ready */
120 LEDs_SetAllLEDs(LEDMASK_USB_NOTREADY);
123 /** Event handler for the USB_ConfigurationChanged event. This is fired when the host sets the current configuration
124 * of the USB device after enumeration - the device endpoints are configured and the mouse reporting task started.
126 void EVENT_USB_Device_ConfigurationChanged(void)
128 bool ConfigSuccess = true;
130 /* Setup HID Report Endpoint */
131 ConfigSuccess &= Endpoint_ConfigureEndpoint(MOUSE_EPADDR, EP_TYPE_INTERRUPT, MOUSE_EPSIZE, 1);
133 /* Turn on Start-of-Frame events for tracking HID report period expiry */
134 USB_Device_EnableSOFEvents();
136 /* Indicate endpoint configuration success or failure */
137 LEDs_SetAllLEDs(ConfigSuccess ? LEDMASK_USB_READY : LEDMASK_USB_ERROR);
140 /** Event handler for the USB_ControlRequest event. This is used to catch and process control requests sent to
141 * the device from the USB host before passing along unhandled control requests to the library for processing
144 void EVENT_USB_Device_ControlRequest(void)
146 /* Handle HID Class specific requests */
147 switch (USB_ControlRequest.bRequest)
149 case HID_REQ_GetReport:
150 if (USB_ControlRequest.bmRequestType == (REQDIR_DEVICETOHOST | REQTYPE_CLASS | REQREC_INTERFACE))
152 USB_MouseReport_Data_t MouseReportData;
154 /* Create the next mouse report for transmission to the host */
155 CreateMouseReport(&MouseReportData);
157 Endpoint_ClearSETUP();
159 /* Write the report data to the control endpoint */
160 Endpoint_Write_Control_Stream_LE(&MouseReportData, sizeof(MouseReportData));
163 /* Clear the report data afterwards */
164 memset(&MouseReportData, 0, sizeof(MouseReportData));
168 case HID_REQ_GetProtocol:
169 if (USB_ControlRequest.bmRequestType == (REQDIR_DEVICETOHOST | REQTYPE_CLASS | REQREC_INTERFACE))
171 Endpoint_ClearSETUP();
173 /* Write the current protocol flag to the host */
174 Endpoint_Write_8(UsingReportProtocol);
177 Endpoint_ClearStatusStage();
181 case HID_REQ_SetProtocol:
182 if (USB_ControlRequest.bmRequestType == (REQDIR_HOSTTODEVICE | REQTYPE_CLASS | REQREC_INTERFACE))
184 Endpoint_ClearSETUP();
185 Endpoint_ClearStatusStage();
187 /* Set or clear the flag depending on what the host indicates that the current Protocol should be */
188 UsingReportProtocol = (USB_ControlRequest.wValue != 0);
192 case HID_REQ_SetIdle:
193 if (USB_ControlRequest.bmRequestType == (REQDIR_HOSTTODEVICE | REQTYPE_CLASS | REQREC_INTERFACE))
195 Endpoint_ClearSETUP();
196 Endpoint_ClearStatusStage();
198 /* Get idle period in MSB, must multiply by 4 to get the duration in milliseconds */
199 IdleCount = ((USB_ControlRequest.wValue & 0xFF00) >> 6);
203 case HID_REQ_GetIdle:
204 if (USB_ControlRequest.bmRequestType == (REQDIR_DEVICETOHOST | REQTYPE_CLASS | REQREC_INTERFACE))
206 Endpoint_ClearSETUP();
208 /* Write the current idle duration to the host, must be divided by 4 before sent to host */
209 Endpoint_Write_8(IdleCount >> 2);
212 Endpoint_ClearStatusStage();
219 /** Event handler for the USB device Start Of Frame event. */
220 void EVENT_USB_Device_StartOfFrame(void)
222 /* One millisecond has elapsed, decrement the idle time remaining counter if it has not already elapsed */
227 /** Fills the given HID report data structure with the next HID report to send to the host.
229 * \param[out] ReportData Pointer to a HID report data structure to be filled
231 void CreateMouseReport(USB_MouseReport_Data_t* const ReportData)
233 uint8_t JoyStatus_LCL = Joystick_GetStatus();
234 uint8_t ButtonStatus_LCL = Buttons_GetStatus();
236 /* Clear the report contents */
237 memset(ReportData, 0, sizeof(USB_MouseReport_Data_t));
239 if (JoyStatus_LCL & JOY_UP)
241 else if (JoyStatus_LCL & JOY_DOWN)
244 if (JoyStatus_LCL & JOY_LEFT)
246 else if (JoyStatus_LCL & JOY_RIGHT)
249 if (JoyStatus_LCL & JOY_PRESS)
250 ReportData->Button |= (1 << 0);
252 if (ButtonStatus_LCL & BUTTONS_BUTTON1)
253 ReportData->Button |= (1 << 1);
256 /** Sends the next HID report to the host, via the keyboard data endpoint. */
257 void SendNextReport(void)
259 static USB_MouseReport_Data_t PrevMouseReportData;
260 USB_MouseReport_Data_t MouseReportData;
263 /* Create the next mouse report for transmission to the host */
264 CreateMouseReport(&MouseReportData);
266 /* Check to see if the report data has changed - if so a report MUST be sent */
267 SendReport = (memcmp(&PrevMouseReportData, &MouseReportData, sizeof(USB_MouseReport_Data_t)) != 0);
269 /* Override the check if the Y or X values are non-zero - we want continuous movement while the joystick
270 * is being held down (via continuous reports), otherwise the cursor will only move once per joystick toggle */
271 if ((MouseReportData.Y != 0) || (MouseReportData.X != 0))
274 /* Check if the idle period is set and has elapsed */
275 if (IdleCount && (!(IdleMSRemaining)))
277 /* Reset the idle time remaining counter */
278 IdleMSRemaining = IdleCount;
280 /* Idle period is set and has elapsed, must send a report to the host */
284 /* Select the Mouse Report Endpoint */
285 Endpoint_SelectEndpoint(MOUSE_EPADDR);
287 /* Check if Mouse Endpoint Ready for Read/Write and if we should send a new report */
288 if (Endpoint_IsReadWriteAllowed() && SendReport)
290 /* Save the current report data for later comparison to check for changes */
291 PrevMouseReportData = MouseReportData;
293 /* Write Mouse Report Data */
294 Endpoint_Write_Stream_LE(&MouseReportData, sizeof(MouseReportData), NULL);
296 /* Finalize the stream transfer to send the last packet */
301 /** Task to manage HID report generation and transmission to the host, when in report mode. */
302 void Mouse_Task(void)
304 /* Device must be connected and configured for the task to run */
305 if (USB_DeviceState != DEVICE_STATE_Configured)
308 /* Send the next mouse report to the host */