Combined Mouse, MouseViaInt and MouseFullInt demos into a single unified demo.
[pub/USBasp.git] / Demos / 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 KeyboardFullInt 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 /* Project Tags, for reading out using the ButtLoad project */
41 BUTTLOADTAG(ProjName, "LUFA Keyboard App");
42 BUTTLOADTAG(BuildTime, __TIME__);
43 BUTTLOADTAG(BuildDate, __DATE__);
44 BUTTLOADTAG(LUFAVersion, "LUFA V" LUFA_VERSION_STRING);
45
46 /* Scheduler Task List */
47 TASK_LIST
48 {
49 #if !defined(INTERRUPT_CONTROL_ENDPOINT)
50 { Task: USB_USBTask , TaskStatus: TASK_STOP },
51 #endif
52
53 #if !defined(INTERRUPT_DATA_ENDPOINT)
54 { Task: USB_Keyboard_Report , TaskStatus: TASK_STOP },
55 #endif
56 };
57
58 /* Global Variables */
59 /** Indicates what report mode the host has requested, true for normal HID reporting mode, false for special boot
60 * protocol reporting mode.
61 */
62 bool UsingReportProtocol = true;
63
64 /** Current Idle period. This is set by the host via a Set Idle HID class request to silence the device's reports
65 * for either the entire idle duration, or until the report status changes (e.g. the user moves the mouse).
66 */
67 uint8_t IdleCount = 0;
68
69 /** Current Idle period remaining. When the IdleCount value is set, this tracks the remaining number of idle
70 * milliseconds. This is seperate to the IdleCount timer and is incremented and compared as the host may request
71 * the current idle period via a Get Idle HID class request, thus its value must be preserved.
72 */
73 uint16_t IdleMSRemaining = 0;
74
75
76 /** Main program entry point. This routine configures the hardware required by the application, then
77 * starts the scheduler to run the USB management task.
78 */
79 int main(void)
80 {
81 /* Disable watchdog if enabled by bootloader/fuses */
82 MCUSR &= ~(1 << WDRF);
83 wdt_disable();
84
85 /* Disable clock division */
86 clock_prescale_set(clock_div_1);
87
88 /* Hardware Initialization */
89 Joystick_Init();
90 LEDs_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 /* Indicate USB enumerating */
117 UpdateStatus(Status_USBEnumerating);
118
119 /* Default to report protocol on connect */
120 UsingReportProtocol = true;
121 }
122
123 /** Event handler for the USB_Reset event. This fires when the USB interface is reset by the USB host, before the
124 * enumeration process begins, and enables the control endpoint interrupt so that control requests can be handled
125 * asynchronously when they arrive rather than when the control endpoint is polled manually.
126 */
127 EVENT_HANDLER(USB_Reset)
128 {
129 #if defined(INTERRUPT_CONTROL_ENDPOINT)
130 /* Select the control endpoint */
131 Endpoint_SelectEndpoint(ENDPOINT_CONTROLEP);
132
133 /* Enable the endpoint SETUP interrupt ISR for the control endpoint */
134 USB_INT_Enable(ENDPOINT_INT_SETUP);
135 #endif
136 }
137
138 /** Event handler for the USB_Disconnect event. This indicates that the device is no longer connected to a host via
139 * the status LEDs.
140 */
141 EVENT_HANDLER(USB_Disconnect)
142 {
143 /* Stop running keyboard reporting and USB management tasks */
144 #if !defined(INTERRUPT_DATA_ENDPOINT)
145 Scheduler_SetTaskMode(USB_Keyboard_Report, TASK_STOP);
146 #endif
147
148 #if !defined(INTERRUPT_CONTROL_ENDPOINT)
149 Scheduler_SetTaskMode(USB_USBTask, TASK_STOP);
150 #endif
151
152 /* Indicate USB not ready */
153 UpdateStatus(Status_USBNotReady);
154 }
155
156 /** Event handler for the USB_ConfigurationChanged event. This is fired when the host sets the current configuration
157 * of the USB device after enumeration, and configures the keyboard device endpoints.
158 */
159 EVENT_HANDLER(USB_ConfigurationChanged)
160 {
161 /* Setup Keyboard Keycode Report Endpoint */
162 Endpoint_ConfigureEndpoint(KEYBOARD_EPNUM, EP_TYPE_INTERRUPT,
163 ENDPOINT_DIR_IN, KEYBOARD_EPSIZE,
164 ENDPOINT_BANK_SINGLE);
165
166 #if defined(INTERRUPT_DATA_ENDPOINT)
167 /* Enable the endpoint IN interrupt ISR for the report endpoint */
168 USB_INT_Enable(ENDPOINT_INT_IN);
169 #endif
170
171 /* Setup Keyboard LED Report Endpoint */
172 Endpoint_ConfigureEndpoint(KEYBOARD_LEDS_EPNUM, EP_TYPE_INTERRUPT,
173 ENDPOINT_DIR_OUT, KEYBOARD_EPSIZE,
174 ENDPOINT_BANK_SINGLE);
175
176 #if defined(INTERRUPT_DATA_ENDPOINT)
177 /* Enable the endpoint OUT interrupt ISR for the LED report endpoint */
178 USB_INT_Enable(ENDPOINT_INT_OUT);
179 #endif
180
181 /* Indicate USB connected and ready */
182 UpdateStatus(Status_USBReady);
183
184 #if !defined(INTERRUPT_DATA_ENDPOINT)
185 /* Start running keyboard reporting task */
186 Scheduler_SetTaskMode(USB_Keyboard_Report, TASK_RUN);
187 #endif
188 }
189
190 /** Event handler for the USB_UnhandledControlPacket event. This is used to catch standard and class specific
191 * control requests that are not handled internally by the USB library (including the HID commands, which are
192 * all issued via the control endpoint), so that they can be handled appropriately for the application.
193 */
194 EVENT_HANDLER(USB_UnhandledControlPacket)
195 {
196 /* Handle HID Class specific requests */
197 switch (bRequest)
198 {
199 case REQ_GetReport:
200 if (bmRequestType == (REQDIR_DEVICETOHOST | REQTYPE_CLASS | REQREC_INTERFACE))
201 {
202 USB_KeyboardReport_Data_t KeyboardReportData;
203
204 /* Create the next keyboard report for transmission to the host */
205 CreateKeyboardReport(&KeyboardReportData);
206
207 /* Ignore report type and ID number value */
208 Endpoint_Discard_Word();
209
210 /* Ignore unused Interface number value */
211 Endpoint_Discard_Word();
212
213 /* Read in the number of bytes in the report to send to the host */
214 uint16_t wLength = Endpoint_Read_Word_LE();
215
216 /* If trying to send more bytes than exist to the host, clamp the value at the report size */
217 if (wLength > sizeof(KeyboardReportData))
218 wLength = sizeof(KeyboardReportData);
219
220 Endpoint_ClearSetupReceived();
221
222 /* Write the report data to the control endpoint */
223 Endpoint_Write_Control_Stream_LE(&KeyboardReportData, wLength);
224
225 /* Finalize the stream transfer to send the last packet or clear the host abort */
226 Endpoint_ClearSetupOUT();
227 }
228
229 break;
230 case REQ_SetReport:
231 if (bmRequestType == (REQDIR_HOSTTODEVICE | REQTYPE_CLASS | REQREC_INTERFACE))
232 {
233 Endpoint_ClearSetupReceived();
234
235 /* Wait until the LED report has been sent by the host */
236 while (!(Endpoint_IsSetupOUTReceived()));
237
238 /* Read in the LED report from the host */
239 uint8_t LEDStatus = Endpoint_Read_Byte();
240
241 /* Process the incomming LED report */
242 ProcessLEDReport(LEDStatus);
243
244 /* Clear the endpoint data */
245 Endpoint_ClearSetupOUT();
246
247 /* Acknowledge status stage */
248 while (!(Endpoint_IsSetupINReady()));
249 Endpoint_ClearSetupIN();
250 }
251
252 break;
253 case REQ_GetProtocol:
254 if (bmRequestType == (REQDIR_DEVICETOHOST | REQTYPE_CLASS | REQREC_INTERFACE))
255 {
256 Endpoint_ClearSetupReceived();
257
258 /* Write the current protocol flag to the host */
259 Endpoint_Write_Byte(UsingReportProtocol);
260
261 /* Send the flag to the host */
262 Endpoint_ClearSetupIN();
263
264 /* Acknowledge status stage */
265 while (!(Endpoint_IsSetupOUTReceived()));
266 Endpoint_ClearSetupOUT();
267 }
268
269 break;
270 case REQ_SetProtocol:
271 if (bmRequestType == (REQDIR_HOSTTODEVICE | REQTYPE_CLASS | REQREC_INTERFACE))
272 {
273 /* Read in the wValue parameter containing the new protocol mode */
274 uint16_t wValue = Endpoint_Read_Word_LE();
275
276 Endpoint_ClearSetupReceived();
277
278 /* Set or clear the flag depending on what the host indicates that the current Protocol should be */
279 UsingReportProtocol = (wValue != 0x0000);
280
281 /* Acknowledge status stage */
282 while (!(Endpoint_IsSetupINReady()));
283 Endpoint_ClearSetupIN();
284 }
285
286 break;
287 case REQ_SetIdle:
288 if (bmRequestType == (REQDIR_HOSTTODEVICE | REQTYPE_CLASS | REQREC_INTERFACE))
289 {
290 /* Read in the wValue parameter containing the idle period */
291 uint16_t wValue = Endpoint_Read_Word_LE();
292
293 Endpoint_ClearSetupReceived();
294
295 /* Get idle period in MSB */
296 IdleCount = (wValue >> 8);
297
298 /* Acknowledge status stage */
299 while (!(Endpoint_IsSetupINReady()));
300 Endpoint_ClearSetupIN();
301 }
302
303 break;
304 case REQ_GetIdle:
305 if (bmRequestType == (REQDIR_DEVICETOHOST | REQTYPE_CLASS | REQREC_INTERFACE))
306 {
307 Endpoint_ClearSetupReceived();
308
309 /* Write the current idle duration to the host */
310 Endpoint_Write_Byte(IdleCount);
311
312 /* Send the flag to the host */
313 Endpoint_ClearSetupIN();
314
315 /* Acknowledge status stage */
316 while (!(Endpoint_IsSetupOUTReceived()));
317 Endpoint_ClearSetupOUT();
318 }
319
320 break;
321 }
322 }
323
324 /** ISR for the timer 0 compare vector. This ISR fires once each millisecond, and increments the
325 * scheduler elapsed idle period counter when the host has set an idle period.
326 */
327 ISR(TIMER0_COMPA_vect, ISR_BLOCK)
328 {
329 /* One millisecond has elapsed, decrement the idle time remaining counter if it has not already elapsed */
330 if (IdleMSRemaining)
331 IdleMSRemaining--;
332 }
333
334 /** Fills the given HID report data structure with the next HID report to send to the host.
335 *
336 * \param ReportData Pointer to a HID report data structure to be filled
337 *
338 * \return Boolean true if the new report differs from the last report, false otherwise
339 */
340 bool CreateKeyboardReport(USB_KeyboardReport_Data_t* ReportData)
341 {
342 static uint8_t PrevJoyStatus = 0;
343 uint8_t JoyStatus_LCL = Joystick_GetStatus();
344 bool InputChanged = false;
345
346 /* Clear the report contents */
347 memset(ReportData, 0, sizeof(USB_KeyboardReport_Data_t));
348
349 if (JoyStatus_LCL & JOY_UP)
350 ReportData->KeyCode[0] = 0x04; // A
351 else if (JoyStatus_LCL & JOY_DOWN)
352 ReportData->KeyCode[0] = 0x05; // B
353
354 if (JoyStatus_LCL & JOY_LEFT)
355 ReportData->KeyCode[0] = 0x06; // C
356 else if (JoyStatus_LCL & JOY_RIGHT)
357 ReportData->KeyCode[0] = 0x07; // D
358
359 if (JoyStatus_LCL & JOY_PRESS)
360 ReportData->KeyCode[0] = 0x08; // E
361
362 /* Check if the new report is different to the previous report */
363 InputChanged = (uint8_t)(PrevJoyStatus ^ JoyStatus_LCL);
364
365 /* Save the current joystick status for later comparison */
366 PrevJoyStatus = JoyStatus_LCL;
367
368 /* Return whether the new report is different to the previous report or not */
369 return InputChanged;
370 }
371
372 /** Processes a received LED report, and updates the board LEDs states to match.
373 *
374 * \param LEDReport LED status report from the host
375 */
376 void ProcessLEDReport(uint8_t LEDReport)
377 {
378 uint8_t LEDMask = LEDS_LED2;
379
380 if (LEDReport & 0x01) // NUM Lock
381 LEDMask |= LEDS_LED1;
382
383 if (LEDReport & 0x02) // CAPS Lock
384 LEDMask |= LEDS_LED3;
385
386 if (LEDReport & 0x04) // SCROLL Lock
387 LEDMask |= LEDS_LED4;
388
389 /* Set the status LEDs to the current Keyboard LED status */
390 LEDs_SetAllLEDs(LEDMask);
391 }
392
393 /** Sends the next HID report to the host, via the keyboard data endpoint. */
394 static inline void SendNextReport(void)
395 {
396 USB_KeyboardReport_Data_t KeyboardReportData;
397 bool SendReport;
398
399 /* Create the next keyboard report for transmission to the host */
400 SendReport = CreateKeyboardReport(&KeyboardReportData);
401
402 /* Check if the idle period is set and has elapsed */
403 if (IdleCount && !(IdleMSRemaining))
404 {
405 /* Idle period elapsed, indicate that a report must be sent */
406 SendReport = true;
407
408 /* Reset the idle time remaining counter, must multiply by 4 to get the duration in milliseconds */
409 IdleMSRemaining = (IdleCount << 2);
410 }
411
412 /* Select the Keyboard Report Endpoint */
413 Endpoint_SelectEndpoint(KEYBOARD_EPNUM);
414
415 /* Check if Keyboard Endpoint Ready for Read/Write, and if we should send a report */
416 if (Endpoint_ReadWriteAllowed() && SendReport)
417 {
418 /* Write Keyboard Report Data */
419 Endpoint_Write_Stream_LE(&KeyboardReportData, sizeof(KeyboardReportData));
420
421 /* Finalize the stream transfer to send the last packet */
422 Endpoint_ClearCurrentBank();
423 }
424 }
425
426 /** Reads the next LED status report from the host from the LED data endpoint, if one has been sent. */
427 static inline void ReceiveNextReport(void)
428 {
429 /* Select the Keyboard LED Report Endpoint */
430 Endpoint_SelectEndpoint(KEYBOARD_LEDS_EPNUM);
431
432 /* Check if Keyboard LED Endpoint Ready for Read/Write */
433 if (!(Endpoint_ReadWriteAllowed()))
434 return;
435
436 /* Read in the LED report from the host */
437 uint8_t LEDReport = Endpoint_Read_Byte();
438
439 /* Handshake the OUT Endpoint - clear endpoint and ready for next report */
440 Endpoint_ClearCurrentBank();
441
442 /* Process the read LED report from the host */
443 ProcessLEDReport(LEDReport);
444 }
445
446 /** Function to manage status updates to the user. This is done via LEDs on the given board, if available, but may be changed to
447 * log to a serial port, or anything else that is suitable for status updates.
448 *
449 * \param CurrentStatus Current status of the system, from the KeyboardFullInt_StatusCodes_t enum
450 */
451 void UpdateStatus(uint8_t CurrentStatus)
452 {
453 uint8_t LEDMask = LEDS_NO_LEDS;
454
455 /* Set the LED mask to the appropriate LED mask based on the given status code */
456 switch (CurrentStatus)
457 {
458 case Status_USBNotReady:
459 LEDMask = (LEDS_LED1);
460 break;
461 case Status_USBEnumerating:
462 LEDMask = (LEDS_LED1 | LEDS_LED2);
463 break;
464 case Status_USBReady:
465 LEDMask = (LEDS_LED2 | LEDS_LED4);
466 break;
467 }
468
469 /* Set the board LEDs to the new LED mask */
470 LEDs_SetAllLEDs(LEDMask);
471 }
472
473 #if !defined(INTERRUPT_DATA_ENDPOINT)
474 /** Function to manage HID report generation and transmission to the host, when in report mode. */
475 TASK(USB_Keyboard_Report)
476 {
477 /* Check if the USB system is connected to a host */
478 if (USB_IsConnected)
479 {
480 /* Send the next keypress report to the host */
481 SendNextReport();
482
483 /* Process the LED report sent from the host */
484 ReceiveNextReport();
485 }
486 }
487 #endif
488
489 /** ISR for the general Pipe/Endpoint interrupt vector. This ISR fires when an endpoint's status changes (such as
490 * a packet has been received) on an endpoint with its corresponding ISR enabling bits set. This is used to send
491 * HID packets to the host each time the HID interrupt endpoints polling period elapses, as managed by the USB
492 * controller. It is also used to respond to standard and class specific requests send to the device on the control
493 * endpoint, by handing them off to the LUFA library when they are received.
494 */
495 ISR(ENDPOINT_PIPE_vect, ISR_BLOCK)
496 {
497 #if defined(INTERRUPT_CONTROL_ENDPOINT)
498 /* Check if the control endpoint has received a request */
499 if (Endpoint_HasEndpointInterrupted(ENDPOINT_CONTROLEP))
500 {
501 /* Clear the endpoint interrupt */
502 Endpoint_ClearEndpointInterrupt(ENDPOINT_CONTROLEP);
503
504 /* Process the control request */
505 USB_USBTask();
506
507 /* Handshake the endpoint setup interrupt - must be after the call to USB_USBTask() */
508 USB_INT_Clear(ENDPOINT_INT_SETUP);
509 }
510 #endif
511
512 #if defined(INTERRUPT_DATA_ENDPOINT)
513 /* Check if keyboard endpoint has interrupted */
514 if (Endpoint_HasEndpointInterrupted(KEYBOARD_EPNUM))
515 {
516 /* Select the Keyboard Report Endpoint */
517 Endpoint_SelectEndpoint(KEYBOARD_EPNUM);
518
519 /* Clear the endpoint IN interrupt flag */
520 USB_INT_Clear(ENDPOINT_INT_IN);
521
522 /* Clear the Keyboard Report endpoint interrupt */
523 Endpoint_ClearEndpointInterrupt(KEYBOARD_EPNUM);
524
525 /* Send the next keypress report to the host */
526 SendNextReport();
527 }
528
529 /* Check if Keyboard LED status Endpoint has interrupted */
530 if (Endpoint_HasEndpointInterrupted(KEYBOARD_LEDS_EPNUM))
531 {
532 /* Select the Keyboard LED Report Endpoint */
533 Endpoint_SelectEndpoint(KEYBOARD_LEDS_EPNUM);
534
535 /* Clear the endpoint OUT interrupt flag */
536 USB_INT_Clear(ENDPOINT_INT_OUT);
537
538 /* Clear the Keyboard LED Report endpoint interrupt */
539 Endpoint_ClearEndpointInterrupt(KEYBOARD_LEDS_EPNUM);
540
541 /* Process the LED report sent from the host */
542 ReceiveNextReport();
543 }
544 #endif
545 }
546