Added stdio.h stream examples for the virtual CDC UART in the CDC host demos.
[pub/USBasp.git] / Demos / Device / LowLevel / Keyboard / Keyboard.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 Denver Gingerich (denver [at] ossguy [dot] com)
11 Based on code by Dean Camera (dean [at] fourwalledcubicle [dot] com)
12
13 Permission to use, copy, modify, and distribute this software
14 and its documentation for any purpose and without fee is hereby
15 granted, provided that the above copyright notice appear in all
16 copies and that both that the copyright notice and this
17 permission notice and warranty disclaimer appear in supporting
18 documentation, and that the name of the author not be used in
19 advertising or publicity pertaining to distribution of the
20 software without specific, written prior permission.
21
22 The author disclaim all warranties with regard to this
23 software, including all implied warranties of merchantability
24 and fitness. In no event shall the author be liable for any
25 special, indirect or consequential damages or any damages
26 whatsoever resulting from loss of use, data or profits, whether
27 in an action of contract, negligence or other tortious action,
28 arising out of or in connection with the use or performance of
29 this software.
30 */
31
32 /** \file
33 *
34 * Main source file for the Keyboard demo. This file contains the main tasks of the demo and
35 * is responsible for the initial application hardware configuration.
36 */
37
38 #include "Keyboard.h"
39
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 presses a key).
47 */
48 uint16_t IdleCount = 500;
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 * enters a loop to run the application tasks in sequence.
59 */
60 int main(void)
61 {
62 SetupHardware();
63
64 LEDs_SetAllLEDs(LEDMASK_USB_NOTREADY);
65
66 for (;;)
67 {
68 HID_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 USB_Init();
87 }
88
89 /** Event handler for the USB_Connect event. This indicates that the device is enumerating via the status LEDs and
90 * starts the library USB task to begin the enumeration and USB management process.
91 */
92 void EVENT_USB_Device_Connect(void)
93 {
94 /* Indicate USB enumerating */
95 LEDs_SetAllLEDs(LEDMASK_USB_ENUMERATING);
96
97 /* Default to report protocol on connect */
98 UsingReportProtocol = true;
99 }
100
101 /** Event handler for the USB_Disconnect event. This indicates that the device is no longer connected to a host via
102 * the status LEDs.
103 */
104 void EVENT_USB_Device_Disconnect(void)
105 {
106 /* Indicate USB not ready */
107 LEDs_SetAllLEDs(LEDMASK_USB_NOTREADY);
108 }
109
110 /** Event handler for the USB_ConfigurationChanged event. This is fired when the host sets the current configuration
111 * of the USB device after enumeration, and configures the keyboard device endpoints.
112 */
113 void EVENT_USB_Device_ConfigurationChanged(void)
114 {
115 /* Indicate USB connected and ready */
116 LEDs_SetAllLEDs(LEDMASK_USB_READY);
117
118 /* Setup Keyboard Keycode Report Endpoint */
119 if (!(Endpoint_ConfigureEndpoint(KEYBOARD_EPNUM, EP_TYPE_INTERRUPT,
120 ENDPOINT_DIR_IN, KEYBOARD_EPSIZE,
121 ENDPOINT_BANK_SINGLE)))
122 {
123 LEDs_SetAllLEDs(LEDMASK_USB_ERROR);
124 }
125
126 /* Setup Keyboard LED Report Endpoint */
127 if (!(Endpoint_ConfigureEndpoint(KEYBOARD_LEDS_EPNUM, EP_TYPE_INTERRUPT,
128 ENDPOINT_DIR_OUT, KEYBOARD_EPSIZE,
129 ENDPOINT_BANK_SINGLE)))
130 {
131 LEDs_SetAllLEDs(LEDMASK_USB_ERROR);
132 }
133
134 USB_Device_EnableSOFEvents();
135 }
136
137 /** Event handler for the USB_UnhandledControlRequest event. This is used to catch standard and class specific
138 * control requests that are not handled internally by the USB library (including the HID commands, which are
139 * all issued via the control endpoint), so that they can be handled appropriately for the application.
140 */
141 void EVENT_USB_Device_UnhandledControlRequest(void)
142 {
143 /* Handle HID Class specific requests */
144 switch (USB_ControlRequest.bRequest)
145 {
146 case REQ_GetReport:
147 if (USB_ControlRequest.bmRequestType == (REQDIR_DEVICETOHOST | REQTYPE_CLASS | REQREC_INTERFACE))
148 {
149 USB_KeyboardReport_Data_t KeyboardReportData;
150
151 Endpoint_ClearSETUP();
152
153 /* Create the next keyboard report for transmission to the host */
154 CreateKeyboardReport(&KeyboardReportData);
155
156 /* Write the report data to the control endpoint */
157 Endpoint_Write_Control_Stream_LE(&KeyboardReportData, sizeof(KeyboardReportData));
158
159 /* Finalize the stream transfer to send the last packet or clear the host abort */
160 Endpoint_ClearOUT();
161 }
162
163 break;
164 case REQ_SetReport:
165 if (USB_ControlRequest.bmRequestType == (REQDIR_HOSTTODEVICE | REQTYPE_CLASS | REQREC_INTERFACE))
166 {
167 Endpoint_ClearSETUP();
168
169 /* Wait until the LED report has been sent by the host */
170 while (!(Endpoint_IsOUTReceived()))
171 {
172 if (USB_DeviceState == DEVICE_STATE_Unattached)
173 return;
174 }
175
176 /* Read in the LED report from the host */
177 uint8_t LEDStatus = Endpoint_Read_Byte();
178
179 /* Process the incoming LED report */
180 ProcessLEDReport(LEDStatus);
181
182 /* Clear the endpoint data */
183 Endpoint_ClearOUT();
184
185 Endpoint_ClearStatusStage();
186 }
187
188 break;
189 case REQ_GetProtocol:
190 if (USB_ControlRequest.bmRequestType == (REQDIR_DEVICETOHOST | REQTYPE_CLASS | REQREC_INTERFACE))
191 {
192 Endpoint_ClearSETUP();
193
194 /* Write the current protocol flag to the host */
195 Endpoint_Write_Byte(UsingReportProtocol);
196
197 /* Send the flag to the host */
198 Endpoint_ClearIN();
199
200 Endpoint_ClearStatusStage();
201 }
202
203 break;
204 case REQ_SetProtocol:
205 if (USB_ControlRequest.bmRequestType == (REQDIR_HOSTTODEVICE | REQTYPE_CLASS | REQREC_INTERFACE))
206 {
207 Endpoint_ClearSETUP();
208
209 /* Set or clear the flag depending on what the host indicates that the current Protocol should be */
210 UsingReportProtocol = (USB_ControlRequest.wValue != 0);
211
212 Endpoint_ClearStatusStage();
213 }
214
215 break;
216 case REQ_SetIdle:
217 if (USB_ControlRequest.bmRequestType == (REQDIR_HOSTTODEVICE | REQTYPE_CLASS | REQREC_INTERFACE))
218 {
219 Endpoint_ClearSETUP();
220
221 /* Get idle period in MSB, IdleCount must be multiplied by 4 to get number of milliseconds */
222 IdleCount = ((USB_ControlRequest.wValue & 0xFF00) >> 6);
223
224 Endpoint_ClearStatusStage();
225 }
226
227 break;
228 case REQ_GetIdle:
229 if (USB_ControlRequest.bmRequestType == (REQDIR_DEVICETOHOST | REQTYPE_CLASS | REQREC_INTERFACE))
230 {
231 Endpoint_ClearSETUP();
232
233 /* Write the current idle duration to the host, must be divided by 4 before sent to host */
234 Endpoint_Write_Byte(IdleCount >> 2);
235
236 /* Send the flag to the host */
237 Endpoint_ClearIN();
238
239 Endpoint_ClearStatusStage();
240 }
241
242 break;
243 }
244 }
245
246 /** Event handler for the USB device Start Of Frame event. */
247 void EVENT_USB_Device_StartOfFrame(void)
248 {
249 /* One millisecond has elapsed, decrement the idle time remaining counter if it has not already elapsed */
250 if (IdleMSRemaining)
251 IdleMSRemaining--;
252 }
253
254 /** Fills the given HID report data structure with the next HID report to send to the host.
255 *
256 * \param[out] ReportData Pointer to a HID report data structure to be filled
257 */
258 void CreateKeyboardReport(USB_KeyboardReport_Data_t* ReportData)
259 {
260 uint8_t JoyStatus_LCL = Joystick_GetStatus();
261
262 /* Clear the report contents */
263 memset(ReportData, 0, sizeof(USB_KeyboardReport_Data_t));
264
265 if (JoyStatus_LCL & JOY_UP)
266 ReportData->KeyCode[0] = 0x04; // A
267 else if (JoyStatus_LCL & JOY_DOWN)
268 ReportData->KeyCode[0] = 0x05; // B
269
270 if (JoyStatus_LCL & JOY_LEFT)
271 ReportData->KeyCode[0] = 0x06; // C
272 else if (JoyStatus_LCL & JOY_RIGHT)
273 ReportData->KeyCode[0] = 0x07; // D
274
275 if (JoyStatus_LCL & JOY_PRESS)
276 ReportData->KeyCode[0] = 0x08; // E
277 }
278
279 /** Processes a received LED report, and updates the board LEDs states to match.
280 *
281 * \param[in] LEDReport LED status report from the host
282 */
283 void ProcessLEDReport(uint8_t LEDReport)
284 {
285 uint8_t LEDMask = LEDS_LED2;
286
287 if (LEDReport & 0x01) // NUM Lock
288 LEDMask |= LEDS_LED1;
289
290 if (LEDReport & 0x02) // CAPS Lock
291 LEDMask |= LEDS_LED3;
292
293 if (LEDReport & 0x04) // SCROLL Lock
294 LEDMask |= LEDS_LED4;
295
296 /* Set the status LEDs to the current Keyboard LED status */
297 LEDs_SetAllLEDs(LEDMask);
298 }
299
300 /** Sends the next HID report to the host, via the keyboard data endpoint. */
301 void SendNextReport(void)
302 {
303 static USB_KeyboardReport_Data_t PrevKeyboardReportData;
304 USB_KeyboardReport_Data_t KeyboardReportData;
305 bool SendReport = true;
306
307 /* Create the next keyboard report for transmission to the host */
308 CreateKeyboardReport(&KeyboardReportData);
309
310 /* Check to see if the report data has changed - if so a report MUST be sent */
311 SendReport = (memcmp(&PrevKeyboardReportData, &KeyboardReportData, sizeof(USB_KeyboardReport_Data_t)) != 0);
312
313 /* Save the current report data for later comparison to check for changes */
314 PrevKeyboardReportData = KeyboardReportData;
315
316 /* Check if the idle period is set and has elapsed */
317 if ((IdleCount != HID_IDLE_CHANGESONLY) && (!(IdleMSRemaining)))
318 {
319 /* Reset the idle time remaining counter */
320 IdleMSRemaining = IdleCount;
321
322 /* Idle period is set and has elapsed, must send a report to the host */
323 SendReport = true;
324 }
325
326 /* Select the Keyboard Report Endpoint */
327 Endpoint_SelectEndpoint(KEYBOARD_EPNUM);
328
329 /* Check if Keyboard Endpoint Ready for Read/Write and if we should send a new report */
330 if (Endpoint_IsReadWriteAllowed() && SendReport)
331 {
332 /* Write Keyboard Report Data */
333 Endpoint_Write_Stream_LE(&KeyboardReportData, sizeof(KeyboardReportData));
334
335 /* Finalize the stream transfer to send the last packet */
336 Endpoint_ClearIN();
337 }
338 }
339
340 /** Reads the next LED status report from the host from the LED data endpoint, if one has been sent. */
341 void ReceiveNextReport(void)
342 {
343 /* Select the Keyboard LED Report Endpoint */
344 Endpoint_SelectEndpoint(KEYBOARD_LEDS_EPNUM);
345
346 /* Check if Keyboard LED Endpoint contains a packet */
347 if (Endpoint_IsOUTReceived())
348 {
349 /* Check to see if the packet contains data */
350 if (Endpoint_IsReadWriteAllowed())
351 {
352 /* Read in the LED report from the host */
353 uint8_t LEDReport = Endpoint_Read_Byte();
354
355 /* Process the read LED report from the host */
356 ProcessLEDReport(LEDReport);
357 }
358
359 /* Handshake the OUT Endpoint - clear endpoint and ready for next report */
360 Endpoint_ClearOUT();
361 }
362 }
363
364 /** Function to manage HID report generation and transmission to the host, when in report mode. */
365 void HID_Task(void)
366 {
367 /* Device must be connected and configured for the task to run */
368 if (USB_DeviceState != DEVICE_STATE_Configured)
369 return;
370
371 /* Send the next keypress report to the host */
372 SendNextReport();
373
374 /* Process the LED report sent from the host */
375 ReceiveNextReport();
376 }