Remove outdated AVRStudio project files from demos, projects, bootloaders. Fix makefi...
[pub/USBasp.git] / Demos / Device / LowLevel / 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 /* Scheduler Task List */
40 TASK_LIST
41 {
42 { .Task = USB_USBTask , .TaskStatus = TASK_STOP },
43 { .Task = USB_Mouse_Report , .TaskStatus = TASK_STOP },
44 };
45
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.
49 */
50 bool UsingReportProtocol = true;
51
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).
54 */
55 uint16_t IdleCount = HID_IDLE_CHANGESONLY;
56
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.
60 */
61 uint16_t IdleMSRemaining = 0;
62
63
64 /** Main program entry point. This routine configures the hardware required by the application, then
65 * starts the scheduler to run the application tasks.
66 */
67 int main(void)
68 {
69 /* Disable watchdog if enabled by bootloader/fuses */
70 MCUSR &= ~(1 << WDRF);
71 wdt_disable();
72
73 /* Disable clock division */
74 clock_prescale_set(clock_div_1);
75
76 /* Hardware Initialization */
77 Joystick_Init();
78 LEDs_Init();
79 Buttons_Init();
80
81 /* Millisecond timer initialization, with output compare interrupt enabled for the idle timing */
82 OCR0A = 0x7D;
83 TCCR0A = (1 << WGM01);
84 TCCR0B = ((1 << CS01) | (1 << CS00));
85 TIMSK0 = (1 << OCIE0A);
86
87 /* Indicate USB not ready */
88 UpdateStatus(Status_USBNotReady);
89
90 /* Initialize Scheduler so that it can be used */
91 Scheduler_Init();
92
93 /* Initialize USB Subsystem */
94 USB_Init();
95
96 /* Scheduling - routine never returns, so put this last in the main function */
97 Scheduler_Start();
98 }
99
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.
102 */
103 void EVENT_USB_Connect(void)
104 {
105 /* Start USB management task */
106 Scheduler_SetTaskMode(USB_USBTask, TASK_RUN);
107
108 /* Indicate USB enumerating */
109 UpdateStatus(Status_USBEnumerating);
110
111 /* Default to report protocol on connect */
112 UsingReportProtocol = true;
113 }
114
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.
117 */
118 void EVENT_USB_Disconnect(void)
119 {
120 /* Stop running mouse reporting and USB management tasks */
121 Scheduler_SetTaskMode(USB_Mouse_Report, TASK_STOP);
122 Scheduler_SetTaskMode(USB_USBTask, TASK_STOP);
123
124 /* Indicate USB not ready */
125 UpdateStatus(Status_USBNotReady);
126 }
127
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.
130 */
131 void EVENT_USB_ConfigurationChanged(void)
132 {
133 /* Setup Mouse Report Endpoint */
134 Endpoint_ConfigureEndpoint(MOUSE_EPNUM, EP_TYPE_INTERRUPT,
135 ENDPOINT_DIR_IN, MOUSE_EPSIZE,
136 ENDPOINT_BANK_SINGLE);
137
138 /* Indicate USB connected and ready */
139 UpdateStatus(Status_USBReady);
140
141 /* Start running mouse reporting task */
142 Scheduler_SetTaskMode(USB_Mouse_Report, TASK_RUN);
143 }
144
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.
148 */
149 void EVENT_USB_UnhandledControlPacket(void)
150 {
151 /* Handle HID Class specific requests */
152 switch (USB_ControlRequest.bRequest)
153 {
154 case REQ_GetReport:
155 if (USB_ControlRequest.bmRequestType == (REQDIR_DEVICETOHOST | REQTYPE_CLASS | REQREC_INTERFACE))
156 {
157 USB_MouseReport_Data_t MouseReportData;
158
159 Endpoint_ClearSETUP();
160
161 /* Create the next mouse report for transmission to the host */
162 CreateMouseReport(&MouseReportData);
163
164 /* Write the report data to the control endpoint */
165 Endpoint_Write_Control_Stream_LE(&MouseReportData, sizeof(MouseReportData));
166
167 /* Clear the report data afterwards */
168 memset(&MouseReportData, 0, sizeof(MouseReportData));
169
170 /* Finalize the stream transfer to send the last packet or clear the host abort */
171 Endpoint_ClearOUT();
172 }
173
174 break;
175 case REQ_GetProtocol:
176 if (USB_ControlRequest.bmRequestType == (REQDIR_DEVICETOHOST | REQTYPE_CLASS | REQREC_INTERFACE))
177 {
178 Endpoint_ClearSETUP();
179
180 /* Write the current protocol flag to the host */
181 Endpoint_Write_Byte(UsingReportProtocol);
182
183 /* Send the flag to the host */
184 Endpoint_ClearIN();
185
186 /* Acknowledge status stage */
187 while (!(Endpoint_IsOUTReceived()));
188 Endpoint_ClearOUT();
189 }
190
191 break;
192 case REQ_SetProtocol:
193 if (USB_ControlRequest.bmRequestType == (REQDIR_HOSTTODEVICE | REQTYPE_CLASS | REQREC_INTERFACE))
194 {
195 Endpoint_ClearSETUP();
196
197 /* Set or clear the flag depending on what the host indicates that the current Protocol should be */
198 UsingReportProtocol = (USB_ControlRequest.wValue != 0);
199
200 /* Acknowledge status stage */
201 while (!(Endpoint_IsINReady()));
202 Endpoint_ClearIN();
203 }
204
205 break;
206 case REQ_SetIdle:
207 if (USB_ControlRequest.bmRequestType == (REQDIR_HOSTTODEVICE | REQTYPE_CLASS | REQREC_INTERFACE))
208 {
209 Endpoint_ClearSETUP();
210
211 /* Get idle period in MSB */
212 IdleCount = (USB_ControlRequest.wValue >> 8);
213
214 /* Acknowledge status stage */
215 while (!(Endpoint_IsINReady()));
216 Endpoint_ClearIN();
217 }
218
219 break;
220 case REQ_GetIdle:
221 if (USB_ControlRequest.bmRequestType == (REQDIR_DEVICETOHOST | REQTYPE_CLASS | REQREC_INTERFACE))
222 {
223 Endpoint_ClearSETUP();
224
225 /* Write the current idle duration to the host */
226 Endpoint_Write_Byte(IdleCount);
227
228 /* Send the flag to the host */
229 Endpoint_ClearIN();
230
231 /* Acknowledge status stage */
232 while (!(Endpoint_IsOUTReceived()));
233 Endpoint_ClearOUT();
234 }
235
236 break;
237 }
238 }
239
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.
242 */
243 ISR(TIMER0_COMPA_vect, ISR_BLOCK)
244 {
245 /* One millisecond has elapsed, decrement the idle time remaining counter if it has not already elapsed */
246 if (IdleMSRemaining)
247 IdleMSRemaining--;
248 }
249
250 /** Fills the given HID report data structure with the next HID report to send to the host.
251 *
252 * \param ReportData Pointer to a HID report data structure to be filled
253 */
254 void CreateMouseReport(USB_MouseReport_Data_t* ReportData)
255 {
256 uint8_t JoyStatus_LCL = Joystick_GetStatus();
257 uint8_t ButtonStatus_LCL = Buttons_GetStatus();
258
259 /* Clear the report contents */
260 memset(ReportData, 0, sizeof(USB_MouseReport_Data_t));
261
262 if (JoyStatus_LCL & JOY_UP)
263 ReportData->Y = -1;
264 else if (JoyStatus_LCL & JOY_DOWN)
265 ReportData->Y = 1;
266
267 if (JoyStatus_LCL & JOY_RIGHT)
268 ReportData->X = 1;
269 else if (JoyStatus_LCL & JOY_LEFT)
270 ReportData->X = -1;
271
272 if (JoyStatus_LCL & JOY_PRESS)
273 ReportData->Button = (1 << 0);
274
275 if (ButtonStatus_LCL & BUTTONS_BUTTON1)
276 ReportData->Button |= (1 << 1);
277 }
278
279 /** Sends the next HID report to the host, via the keyboard data endpoint. */
280 void SendNextReport(void)
281 {
282 static USB_MouseReport_Data_t PrevMouseReportData;
283 USB_MouseReport_Data_t MouseReportData;
284 bool SendReport;
285
286 /* Create the next mouse report for transmission to the host */
287 CreateMouseReport(&MouseReportData);
288
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);
291
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))
295 SendReport = true;
296
297 /* Save the current report data for later comparison to check for changes */
298 PrevMouseReportData = MouseReportData;
299
300 /* Check if the idle period is set and has elapsed */
301 if ((IdleCount != HID_IDLE_CHANGESONLY) && (!(IdleMSRemaining)))
302 {
303 /* Reset the idle time remaining counter, must multiply by 4 to get the duration in milliseconds */
304 IdleMSRemaining = (IdleCount << 2);
305
306 /* Idle period is set and has elapsed, must send a report to the host */
307 SendReport = true;
308 }
309
310 /* Select the Mouse Report Endpoint */
311 Endpoint_SelectEndpoint(MOUSE_EPNUM);
312
313 /* Check if Mouse Endpoint Ready for Read/Write and if we should send a new report */
314 if (Endpoint_IsReadWriteAllowed() && SendReport)
315 {
316 /* Write Mouse Report Data */
317 Endpoint_Write_Stream_LE(&MouseReportData, sizeof(MouseReportData));
318
319 /* Finalize the stream transfer to send the last packet */
320 Endpoint_ClearIN();
321 }
322 }
323
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.
326 *
327 * \param CurrentStatus Current status of the system, from the Mouse_StatusCodes_t enum
328 */
329 void UpdateStatus(uint8_t CurrentStatus)
330 {
331 uint8_t LEDMask = LEDS_NO_LEDS;
332
333 /* Set the LED mask to the appropriate LED mask based on the given status code */
334 switch (CurrentStatus)
335 {
336 case Status_USBNotReady:
337 LEDMask = (LEDS_LED1);
338 break;
339 case Status_USBEnumerating:
340 LEDMask = (LEDS_LED1 | LEDS_LED2);
341 break;
342 case Status_USBReady:
343 LEDMask = (LEDS_LED2 | LEDS_LED4);
344 break;
345 }
346
347 /* Set the board LEDs to the new LED mask */
348 LEDs_SetAllLEDs(LEDMask);
349 }
350
351 /** Task to manage HID report generation and transmission to the host, when in report mode. */
352 TASK(USB_Mouse_Report)
353 {
354 /* Check if the USB system is connected to a host */
355 if (USB_IsConnected)
356 {
357 /* Send the next mouse report to the host */
358 SendNextReport();
359 }
360 }