Combined Mouse, MouseViaInt and MouseFullInt demos into a single unified demo.
[pub/USBasp.git] / Demos / Mouse / Mouse.c
1 /*
2 LUFA Library
3 Copyright (C) Dean Camera, 2009.
4
5 dean [at] fourwalledcubicle [dot] com
6 www.fourwalledcubicle.com
7 */
8
9 /*
10 Copyright 2009 Dean Camera (dean [at] fourwalledcubicle [dot] com)
11
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.
20
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
28 this software.
29 */
30
31 /** \file
32 *
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.
35 */
36
37 #include "Mouse.h"
38
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);
44
45 /* Scheduler Task List */
46 TASK_LIST
47 {
48 #if !defined(INTERRUPT_CONTROL_ENDPOINT)
49 { Task: USB_USBTask , TaskStatus: TASK_STOP },
50 #endif
51
52 #if !defined(INTERRUPT_DATA_ENDPOINT)
53 { Task: USB_Mouse_Report , TaskStatus: TASK_STOP },
54 #endif
55 };
56
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.
60 */
61 bool UsingReportProtocol = true;
62
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).
65 */
66 uint8_t IdleCount = 0;
67
68 /** Current Idle period remaining. When the IdleCount value is set, this tracks the remaining number of idle
69 * milliseconds. This is seperate 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.
71 */
72 uint16_t IdleMSRemaining = 0;
73
74
75 /** Main program entry point. This routine configures the hardware required by the application, then
76 * starts the scheduler to run the application tasks.
77 */
78 int main(void)
79 {
80 /* Disable watchdog if enabled by bootloader/fuses */
81 MCUSR &= ~(1 << WDRF);
82 wdt_disable();
83
84 /* Disable clock division */
85 clock_prescale_set(clock_div_1);
86
87 /* Hardware Initialization */
88 Joystick_Init();
89 LEDs_Init();
90 HWB_Init();
91
92 /* Millisecond timer initialization, with output compare interrupt enabled for the idle timing */
93 OCR0A = 0x7D;
94 TCCR0A = (1 << WGM01);
95 TCCR0B = ((1 << CS01) | (1 << CS00));
96 TIMSK0 = (1 << OCIE0A);
97
98 /* Indicate USB not ready */
99 UpdateStatus(Status_USBNotReady);
100
101 /* Initialize Scheduler so that it can be used */
102 Scheduler_Init();
103
104 /* Initialize USB Subsystem */
105 USB_Init();
106
107 /* Scheduling - routine never returns, so put this last in the main function */
108 Scheduler_Start();
109 }
110
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.
113 */
114 EVENT_HANDLER(USB_Connect)
115 {
116 /* Start USB management task */
117 Scheduler_SetTaskMode(USB_USBTask, TASK_RUN);
118
119 /* Indicate USB enumerating */
120 UpdateStatus(Status_USBEnumerating);
121
122 /* Default to report protocol on connect */
123 UsingReportProtocol = true;
124 }
125
126 /** Event handler for the USB_Reset event. This fires when the USB interface is reset by the USB host, before the
127 * enumeration process begins, and enables the control endpoint interrupt so that control requests can be handled
128 * asynchronously when they arrive rather than when the control endpoint is polled manually.
129 */
130 EVENT_HANDLER(USB_Reset)
131 {
132 #if defined(INTERRUPT_CONTROL_ENDPOINT)
133 /* Select the control endpoint */
134 Endpoint_SelectEndpoint(ENDPOINT_CONTROLEP);
135
136 /* Enable the endpoint SETUP interrupt ISR for the control endpoint */
137 USB_INT_Enable(ENDPOINT_INT_SETUP);
138 #endif
139 }
140
141 /** Event handler for the USB_Disconnect event. This indicates that the device is no longer connected to a host via
142 * the status LEDs and stops the USB management and Mouse reporting tasks.
143 */
144 EVENT_HANDLER(USB_Disconnect)
145 {
146 /* Stop running keyboard reporting and USB management tasks */
147 #if !defined(INTERRUPT_DATA_ENDPOINT)
148 Scheduler_SetTaskMode(USB_Mouse_Report, TASK_STOP);
149 #endif
150
151 #if !defined(INTERRUPT_CONTROL_ENDPOINT)
152 Scheduler_SetTaskMode(USB_USBTask, TASK_STOP);
153 #endif
154
155 /* Indicate USB not ready */
156 UpdateStatus(Status_USBNotReady);
157 }
158
159 /** Event handler for the USB_ConfigurationChanged event. This is fired when the host sets the current configuration
160 * of the USB device after enumeration - the device endpoints are configured and the mouse reporting task started.
161 */
162 EVENT_HANDLER(USB_ConfigurationChanged)
163 {
164 /* Setup Mouse Report Endpoint */
165 Endpoint_ConfigureEndpoint(MOUSE_EPNUM, EP_TYPE_INTERRUPT,
166 ENDPOINT_DIR_IN, MOUSE_EPSIZE,
167 ENDPOINT_BANK_SINGLE);
168
169 #if defined(INTERRUPT_DATA_ENDPOINT)
170 /* Enable the endpoint IN interrupt ISR for the report endpoint */
171 USB_INT_Enable(ENDPOINT_INT_IN);
172 #endif
173
174 /* Indicate USB connected and ready */
175 UpdateStatus(Status_USBReady);
176
177 #if !defined(INTERRUPT_DATA_ENDPOINT)
178 /* Start running mouse reporting task */
179 Scheduler_SetTaskMode(USB_Mouse_Report, TASK_RUN);
180 #endif
181 }
182
183 /** Event handler for the USB_UnhandledControlPacket event. This is used to catch standard and class specific
184 * control requests that are not handled internally by the USB library (including the HID commands, which are
185 * all issued via the control endpoint), so that they can be handled appropriately for the application.
186 */
187 EVENT_HANDLER(USB_UnhandledControlPacket)
188 {
189 /* Handle HID Class specific requests */
190 switch (bRequest)
191 {
192 case REQ_GetReport:
193 if (bmRequestType == (REQDIR_DEVICETOHOST | REQTYPE_CLASS | REQREC_INTERFACE))
194 {
195 USB_MouseReport_Data_t MouseReportData;
196
197 /* Create the next mouse report for transmission to the host */
198 CreateMouseReport(&MouseReportData);
199
200 /* Ignore report type and ID number value */
201 Endpoint_Discard_Word();
202
203 /* Ignore unused Interface number value */
204 Endpoint_Discard_Word();
205
206 /* Read in the number of bytes in the report to send to the host */
207 uint16_t wLength = Endpoint_Read_Word_LE();
208
209 /* If trying to send more bytes than exist to the host, clamp the value at the report size */
210 if (wLength > sizeof(MouseReportData))
211 wLength = sizeof(MouseReportData);
212
213 Endpoint_ClearSetupReceived();
214
215 /* Write the report data to the control endpoint */
216 Endpoint_Write_Control_Stream_LE(&MouseReportData, wLength);
217
218 /* Clear the report data afterwards */
219 memset(&MouseReportData, 0, sizeof(MouseReportData));
220
221 /* Finalize the stream transfer to send the last packet or clear the host abort */
222 Endpoint_ClearSetupOUT();
223 }
224
225 break;
226 case REQ_GetProtocol:
227 if (bmRequestType == (REQDIR_DEVICETOHOST | REQTYPE_CLASS | REQREC_INTERFACE))
228 {
229 Endpoint_ClearSetupReceived();
230
231 /* Write the current protocol flag to the host */
232 Endpoint_Write_Byte(UsingReportProtocol);
233
234 /* Send the flag to the host */
235 Endpoint_ClearSetupIN();
236
237 /* Acknowledge status stage */
238 while (!(Endpoint_IsSetupOUTReceived()));
239 Endpoint_ClearSetupOUT();
240 }
241
242 break;
243 case REQ_SetProtocol:
244 if (bmRequestType == (REQDIR_HOSTTODEVICE | REQTYPE_CLASS | REQREC_INTERFACE))
245 {
246 /* Read in the wValue parameter containing the new protocol mode */
247 uint16_t wValue = Endpoint_Read_Word_LE();
248
249 Endpoint_ClearSetupReceived();
250
251 /* Set or clear the flag depending on what the host indicates that the current Protocol should be */
252 UsingReportProtocol = (wValue != 0x0000);
253
254 /* Acknowledge status stage */
255 while (!(Endpoint_IsSetupINReady()));
256 Endpoint_ClearSetupIN();
257 }
258
259 break;
260 case REQ_SetIdle:
261 if (bmRequestType == (REQDIR_HOSTTODEVICE | REQTYPE_CLASS | REQREC_INTERFACE))
262 {
263 /* Read in the wValue parameter containing the idle period */
264 uint16_t wValue = Endpoint_Read_Word_LE();
265
266 Endpoint_ClearSetupReceived();
267
268 /* Get idle period in MSB */
269 IdleCount = (wValue >> 8);
270
271 /* Acknowledge status stage */
272 while (!(Endpoint_IsSetupINReady()));
273 Endpoint_ClearSetupIN();
274 }
275
276 break;
277 case REQ_GetIdle:
278 if (bmRequestType == (REQDIR_DEVICETOHOST | REQTYPE_CLASS | REQREC_INTERFACE))
279 {
280 Endpoint_ClearSetupReceived();
281
282 /* Write the current idle duration to the host */
283 Endpoint_Write_Byte(IdleCount);
284
285 /* Send the flag to the host */
286 Endpoint_ClearSetupIN();
287
288 /* Acknowledge status stage */
289 while (!(Endpoint_IsSetupOUTReceived()));
290 Endpoint_ClearSetupOUT();
291 }
292
293 break;
294 }
295 }
296
297 /** ISR for the timer 0 compare vector. This ISR fires once each millisecond, and increments the
298 * scheduler elapsed idle period counter when the host has set an idle period.
299 */
300 ISR(TIMER0_COMPA_vect, ISR_BLOCK)
301 {
302 /* One millisecond has elapsed, decrement the idle time remaining counter if it has not already elapsed */
303 if (IdleMSRemaining)
304 IdleMSRemaining--;
305 }
306
307 /** Fills the given HID report data structure with the next HID report to send to the host.
308 *
309 * \param ReportData Pointer to a HID report data structure to be filled
310 *
311 * \return Boolean true if the new report differs from the last report, false otherwise
312 */
313 bool CreateMouseReport(USB_MouseReport_Data_t* ReportData)
314 {
315 static uint8_t PrevJoyStatus = 0;
316 static bool PrevHWBStatus = false;
317 uint8_t JoyStatus_LCL = Joystick_GetStatus();
318 bool InputChanged = false;
319
320 /* Clear the report contents */
321 memset(ReportData, 0, sizeof(USB_MouseReport_Data_t));
322
323 if (JoyStatus_LCL & JOY_UP)
324 ReportData->Y = -1;
325 else if (JoyStatus_LCL & JOY_DOWN)
326 ReportData->Y = 1;
327
328 if (JoyStatus_LCL & JOY_RIGHT)
329 ReportData->X = 1;
330 else if (JoyStatus_LCL & JOY_LEFT)
331 ReportData->X = -1;
332
333 if (JoyStatus_LCL & JOY_PRESS)
334 ReportData->Button = (1 << 0);
335
336 if (HWB_GetStatus())
337 ReportData->Button |= (1 << 1);
338
339 /* Check if the new report is different to the previous report */
340 InputChanged = ((uint8_t)(PrevJoyStatus ^ JoyStatus_LCL) | (uint8_t)(HWB_GetStatus() ^ PrevHWBStatus));
341
342 /* Save the current joystick and HWB status for later comparison */
343 PrevJoyStatus = JoyStatus_LCL;
344 PrevHWBStatus = HWB_GetStatus();
345
346 /* Return whether the new report is different to the previous report or not */
347 return InputChanged;
348 }
349
350 /** Sends the next HID report to the host, via the keyboard data endpoint. */
351 static inline void SendNextReport(void)
352 {
353 USB_MouseReport_Data_t MouseReportData;
354 bool SendReport = true;
355
356 /* Create the next mouse report for transmission to the host */
357 CreateMouseReport(&MouseReportData);
358
359 /* Check if the idle period is set*/
360 if (IdleCount)
361 {
362 /* Determine if the idle period has elapsed */
363 if (!(IdleMSRemaining))
364 {
365 /* Reset the idle time remaining counter, must multiply by 4 to get the duration in milliseconds */
366 IdleMSRemaining = (IdleCount << 2);
367 }
368 else
369 {
370 /* Idle period not elapsed, indicate that a report must not be sent */
371 SendReport = false;
372 }
373 }
374
375 /* Select the Mouse Report Endpoint */
376 Endpoint_SelectEndpoint(MOUSE_EPNUM);
377
378 /* Check if Mouse Endpoint Ready for Read/Write and if we should send a new report */
379 if (Endpoint_ReadWriteAllowed() && SendReport)
380 {
381 /* Write Mouse Report Data */
382 Endpoint_Write_Stream_LE(&MouseReportData, sizeof(MouseReportData));
383
384 /* Finalize the stream transfer to send the last packet */
385 Endpoint_ClearCurrentBank();
386 }
387 }
388
389 /** Function to manage status updates to the user. This is done via LEDs on the given board, if available, but may be changed to
390 * log to a serial port, or anything else that is suitable for status updates.
391 *
392 * \param CurrentStatus Current status of the system, from the Mouse_StatusCodes_t enum
393 */
394 void UpdateStatus(uint8_t CurrentStatus)
395 {
396 uint8_t LEDMask = LEDS_NO_LEDS;
397
398 /* Set the LED mask to the appropriate LED mask based on the given status code */
399 switch (CurrentStatus)
400 {
401 case Status_USBNotReady:
402 LEDMask = (LEDS_LED1);
403 break;
404 case Status_USBEnumerating:
405 LEDMask = (LEDS_LED1 | LEDS_LED2);
406 break;
407 case Status_USBReady:
408 LEDMask = (LEDS_LED2 | LEDS_LED4);
409 break;
410 }
411
412 /* Set the board LEDs to the new LED mask */
413 LEDs_SetAllLEDs(LEDMask);
414 }
415
416 #if !defined(INTERRUPT_DATA_ENDPOINT)
417 /** Task to manage HID report generation and transmission to the host, when in report mode. */
418 TASK(USB_Mouse_Report)
419 {
420 /* Check if the USB system is connected to a host */
421 if (USB_IsConnected)
422 {
423 /* Send the next mouse report to the host */
424 SendNextReport();
425 }
426 }
427 #endif
428
429 /** ISR for the general Pipe/Endpoint interrupt vector. This ISR fires when an endpoint's status changes (such as
430 * a packet has been received) on an endpoint with its corresponding ISR enabling bits set. This is used to send
431 * HID packets to the host each time the HID interrupt endpoints polling period elapses, as managed by the USB
432 * controller. It is also used to respond to standard and class specific requests send to the device on the control
433 * endpoint, by handing them off to the LUFA library when they are received.
434 */
435 ISR(ENDPOINT_PIPE_vect, ISR_BLOCK)
436 {
437 #if defined(INTERRUPT_CONTROL_ENDPOINT)
438 /* Check if the control endpoint has received a request */
439 if (Endpoint_HasEndpointInterrupted(ENDPOINT_CONTROLEP))
440 {
441 /* Clear the endpoint interrupt */
442 Endpoint_ClearEndpointInterrupt(ENDPOINT_CONTROLEP);
443
444 /* Process the control request */
445 USB_USBTask();
446
447 /* Handshake the endpoint setup interrupt - must be after the call to USB_USBTask() */
448 USB_INT_Clear(ENDPOINT_INT_SETUP);
449 }
450 #endif
451
452 #if defined(INTERRUPT_DATA_ENDPOINT)
453 /* Check if mouse endpoint has interrupted */
454 if (Endpoint_HasEndpointInterrupted(MOUSE_EPNUM))
455 {
456 /* Select the Mouse Report Endpoint */
457 Endpoint_SelectEndpoint(MOUSE_EPNUM);
458
459 /* Clear the endpoint IN interrupt flag */
460 USB_INT_Clear(ENDPOINT_INT_IN);
461
462 /* Clear the Mouse Report endpoint interrupt and select the endpoint */
463 Endpoint_ClearEndpointInterrupt(MOUSE_EPNUM);
464
465 /* Send the next mouse report to the host */
466 SendNextReport();
467 }
468 #endif
469 }