Converted device mode low-level demos to schedulerless.
[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 /* Global Variables */
40 /** Indicates what report mode the host has requested, true for normal HID reporting mode, false for special boot
41 * protocol reporting mode.
42 */
43 bool UsingReportProtocol = true;
44
45 /** Current Idle period. This is set by the host via a Set Idle HID class request to silence the device's reports
46 * for either the entire idle duration, or until the report status changes (e.g. the user moves the mouse).
47 */
48 uint16_t IdleCount = HID_IDLE_CHANGESONLY;
49
50 /** Current Idle period remaining. When the IdleCount value is set, this tracks the remaining number of idle
51 * milliseconds. This is separate to the IdleCount timer and is incremented and compared as the host may request
52 * the current idle period via a Get Idle HID class request, thus its value must be preserved.
53 */
54 uint16_t IdleMSRemaining = 0;
55
56
57 /** Main program entry point. This routine configures the hardware required by the application, then
58 * starts the scheduler to run the application tasks.
59 */
60 int main(void)
61 {
62 SetupHardware();
63
64 LEDs_SetAllLEDs(LEDMASK_USB_NOTREADY);
65
66 for (;;)
67 {
68 Mouse_Task();
69 USB_USBTask();
70 }
71 }
72
73 /** Configures the board hardware and chip peripherals for the demo's functionality. */
74 void SetupHardware(void)
75 {
76 /* Disable watchdog if enabled by bootloader/fuses */
77 MCUSR &= ~(1 << WDRF);
78 wdt_disable();
79
80 /* Disable clock division */
81 clock_prescale_set(clock_div_1);
82
83 /* Hardware Initialization */
84 Joystick_Init();
85 LEDs_Init();
86 Buttons_Init();
87 USB_Init();
88
89 /* Millisecond timer initialization, with output compare interrupt enabled for the idle timing */
90 OCR0A = 0x7D;
91 TCCR0A = (1 << WGM01);
92 TCCR0B = ((1 << CS01) | (1 << CS00));
93 TIMSK0 = (1 << OCIE0A);
94 }
95
96 /** Event handler for the USB_Connect event. This indicates that the device is enumerating via the status LEDs and
97 * starts the library USB task to begin the enumeration and USB management process.
98 */
99 void EVENT_USB_Connect(void)
100 {
101 /* Indicate USB enumerating */
102 LEDs_SetAllLEDs(LEDMASK_USB_ENUMERATING);
103
104 /* Default to report protocol on connect */
105 UsingReportProtocol = true;
106 }
107
108 /** Event handler for the USB_Disconnect event. This indicates that the device is no longer connected to a host via
109 * the status LEDs and stops the USB management and Mouse reporting tasks.
110 */
111 void EVENT_USB_Disconnect(void)
112 {
113 /* Indicate USB not ready */
114 LEDs_SetAllLEDs(LEDMASK_USB_NOTREADY);
115 }
116
117 /** Event handler for the USB_ConfigurationChanged event. This is fired when the host sets the current configuration
118 * of the USB device after enumeration - the device endpoints are configured and the mouse reporting task started.
119 */
120 void EVENT_USB_ConfigurationChanged(void)
121 {
122 /* Setup Mouse Report Endpoint */
123 Endpoint_ConfigureEndpoint(MOUSE_EPNUM, EP_TYPE_INTERRUPT,
124 ENDPOINT_DIR_IN, MOUSE_EPSIZE,
125 ENDPOINT_BANK_SINGLE);
126
127 /* Indicate USB connected and ready */
128 LEDs_SetAllLEDs(LEDMASK_USB_READY);
129 }
130
131 /** Event handler for the USB_UnhandledControlPacket event. This is used to catch standard and class specific
132 * control requests that are not handled internally by the USB library (including the HID commands, which are
133 * all issued via the control endpoint), so that they can be handled appropriately for the application.
134 */
135 void EVENT_USB_UnhandledControlPacket(void)
136 {
137 /* Handle HID Class specific requests */
138 switch (USB_ControlRequest.bRequest)
139 {
140 case REQ_GetReport:
141 if (USB_ControlRequest.bmRequestType == (REQDIR_DEVICETOHOST | REQTYPE_CLASS | REQREC_INTERFACE))
142 {
143 USB_MouseReport_Data_t MouseReportData;
144
145 Endpoint_ClearSETUP();
146
147 /* Create the next mouse report for transmission to the host */
148 CreateMouseReport(&MouseReportData);
149
150 /* Write the report data to the control endpoint */
151 Endpoint_Write_Control_Stream_LE(&MouseReportData, sizeof(MouseReportData));
152
153 /* Clear the report data afterwards */
154 memset(&MouseReportData, 0, sizeof(MouseReportData));
155
156 /* Finalize the stream transfer to send the last packet or clear the host abort */
157 Endpoint_ClearOUT();
158 }
159
160 break;
161 case REQ_GetProtocol:
162 if (USB_ControlRequest.bmRequestType == (REQDIR_DEVICETOHOST | REQTYPE_CLASS | REQREC_INTERFACE))
163 {
164 Endpoint_ClearSETUP();
165
166 /* Write the current protocol flag to the host */
167 Endpoint_Write_Byte(UsingReportProtocol);
168
169 /* Send the flag to the host */
170 Endpoint_ClearIN();
171
172 /* Acknowledge status stage */
173 while (!(Endpoint_IsOUTReceived()));
174 Endpoint_ClearOUT();
175 }
176
177 break;
178 case REQ_SetProtocol:
179 if (USB_ControlRequest.bmRequestType == (REQDIR_HOSTTODEVICE | REQTYPE_CLASS | REQREC_INTERFACE))
180 {
181 Endpoint_ClearSETUP();
182
183 /* Set or clear the flag depending on what the host indicates that the current Protocol should be */
184 UsingReportProtocol = (USB_ControlRequest.wValue != 0);
185
186 /* Acknowledge status stage */
187 while (!(Endpoint_IsINReady()));
188 Endpoint_ClearIN();
189 }
190
191 break;
192 case REQ_SetIdle:
193 if (USB_ControlRequest.bmRequestType == (REQDIR_HOSTTODEVICE | REQTYPE_CLASS | REQREC_INTERFACE))
194 {
195 Endpoint_ClearSETUP();
196
197 /* Get idle period in MSB */
198 IdleCount = (USB_ControlRequest.wValue >> 8);
199
200 /* Acknowledge status stage */
201 while (!(Endpoint_IsINReady()));
202 Endpoint_ClearIN();
203 }
204
205 break;
206 case REQ_GetIdle:
207 if (USB_ControlRequest.bmRequestType == (REQDIR_DEVICETOHOST | REQTYPE_CLASS | REQREC_INTERFACE))
208 {
209 Endpoint_ClearSETUP();
210
211 /* Write the current idle duration to the host */
212 Endpoint_Write_Byte(IdleCount);
213
214 /* Send the flag to the host */
215 Endpoint_ClearIN();
216
217 /* Acknowledge status stage */
218 while (!(Endpoint_IsOUTReceived()));
219 Endpoint_ClearOUT();
220 }
221
222 break;
223 }
224 }
225
226 /** ISR for the timer 0 compare vector. This ISR fires once each millisecond, and increments the
227 * scheduler elapsed idle period counter when the host has set an idle period.
228 */
229 ISR(TIMER0_COMPA_vect, ISR_BLOCK)
230 {
231 /* One millisecond has elapsed, decrement the idle time remaining counter if it has not already elapsed */
232 if (IdleMSRemaining)
233 IdleMSRemaining--;
234 }
235
236 /** Fills the given HID report data structure with the next HID report to send to the host.
237 *
238 * \param ReportData Pointer to a HID report data structure to be filled
239 */
240 void CreateMouseReport(USB_MouseReport_Data_t* ReportData)
241 {
242 uint8_t JoyStatus_LCL = Joystick_GetStatus();
243 uint8_t ButtonStatus_LCL = Buttons_GetStatus();
244
245 /* Clear the report contents */
246 memset(ReportData, 0, sizeof(USB_MouseReport_Data_t));
247
248 if (JoyStatus_LCL & JOY_UP)
249 ReportData->Y = -1;
250 else if (JoyStatus_LCL & JOY_DOWN)
251 ReportData->Y = 1;
252
253 if (JoyStatus_LCL & JOY_RIGHT)
254 ReportData->X = 1;
255 else if (JoyStatus_LCL & JOY_LEFT)
256 ReportData->X = -1;
257
258 if (JoyStatus_LCL & JOY_PRESS)
259 ReportData->Button = (1 << 0);
260
261 if (ButtonStatus_LCL & BUTTONS_BUTTON1)
262 ReportData->Button |= (1 << 1);
263 }
264
265 /** Sends the next HID report to the host, via the keyboard data endpoint. */
266 void SendNextReport(void)
267 {
268 static USB_MouseReport_Data_t PrevMouseReportData;
269 USB_MouseReport_Data_t MouseReportData;
270 bool SendReport;
271
272 /* Create the next mouse report for transmission to the host */
273 CreateMouseReport(&MouseReportData);
274
275 /* Check to see if the report data has changed - if so a report MUST be sent */
276 SendReport = (memcmp(&PrevMouseReportData, &MouseReportData, sizeof(USB_MouseReport_Data_t)) != 0);
277
278 /* Override the check if the Y or X values are non-zero - we want continuous movement while the joystick
279 * is being held down (via continuous reports), otherwise the cursor will only move once per joystick toggle */
280 if ((MouseReportData.Y != 0) || (MouseReportData.X != 0))
281 SendReport = true;
282
283 /* Save the current report data for later comparison to check for changes */
284 PrevMouseReportData = MouseReportData;
285
286 /* Check if the idle period is set and has elapsed */
287 if ((IdleCount != HID_IDLE_CHANGESONLY) && (!(IdleMSRemaining)))
288 {
289 /* Reset the idle time remaining counter, must multiply by 4 to get the duration in milliseconds */
290 IdleMSRemaining = (IdleCount << 2);
291
292 /* Idle period is set and has elapsed, must send a report to the host */
293 SendReport = true;
294 }
295
296 /* Select the Mouse Report Endpoint */
297 Endpoint_SelectEndpoint(MOUSE_EPNUM);
298
299 /* Check if Mouse Endpoint Ready for Read/Write and if we should send a new report */
300 if (Endpoint_IsReadWriteAllowed() && SendReport)
301 {
302 /* Write Mouse Report Data */
303 Endpoint_Write_Stream_LE(&MouseReportData, sizeof(MouseReportData));
304
305 /* Finalize the stream transfer to send the last packet */
306 Endpoint_ClearIN();
307 }
308 }
309
310 /** Task to manage HID report generation and transmission to the host, when in report mode. */
311 void Mouse_Task(void)
312 {
313 /* Check if the USB system is connected to a host */
314 if (USB_IsConnected)
315 {
316 /* Send the next mouse report to the host */
317 SendNextReport();
318 }
319 }