Rename Drivers/AT90USBXXX to Drivers/Peripheral.
[pub/USBasp.git] / Demos / Device / 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 /* Scheduler Task List */
41 TASK_LIST
42 {
43 #if !defined(INTERRUPT_CONTROL_ENDPOINT)
44 { Task: USB_USBTask , TaskStatus: TASK_STOP },
45 #endif
46
47 #if !defined(INTERRUPT_DATA_ENDPOINT)
48 { Task: USB_Keyboard_Report , TaskStatus: TASK_STOP },
49 #endif
50 };
51
52 /* Global Variables */
53 /** Indicates what report mode the host has requested, true for normal HID reporting mode, false for special boot
54 * protocol reporting mode.
55 */
56 bool UsingReportProtocol = true;
57
58 /** Current Idle period. This is set by the host via a Set Idle HID class request to silence the device's reports
59 * for either the entire idle duration, or until the report status changes (e.g. the user moves the mouse).
60 */
61 uint8_t IdleCount = 0;
62
63 /** Current Idle period remaining. When the IdleCount value is set, this tracks the remaining number of idle
64 * milliseconds. This is separate to the IdleCount timer and is incremented and compared as the host may request
65 * the current idle period via a Get Idle HID class request, thus its value must be preserved.
66 */
67 uint16_t IdleMSRemaining = 0;
68
69
70 /** Main program entry point. This routine configures the hardware required by the application, then
71 * starts the scheduler to run the USB management task.
72 */
73 int main(void)
74 {
75 /* Disable watchdog if enabled by bootloader/fuses */
76 MCUSR &= ~(1 << WDRF);
77 wdt_disable();
78
79 /* Disable clock division */
80 clock_prescale_set(clock_div_1);
81
82 /* Hardware Initialization */
83 Joystick_Init();
84 LEDs_Init();
85
86 /* Millisecond timer initialization, with output compare interrupt enabled for the idle timing */
87 OCR0A = 0x7D;
88 TCCR0A = (1 << WGM01);
89 TCCR0B = ((1 << CS01) | (1 << CS00));
90 TIMSK0 = (1 << OCIE0A);
91
92 /* Indicate USB not ready */
93 UpdateStatus(Status_USBNotReady);
94
95 /* Initialize Scheduler so that it can be used */
96 Scheduler_Init();
97
98 /* Initialize USB Subsystem */
99 USB_Init();
100
101 /* Scheduling - routine never returns, so put this last in the main function */
102 Scheduler_Start();
103 }
104
105 /** Event handler for the USB_Connect event. This indicates that the device is enumerating via the status LEDs and
106 * starts the library USB task to begin the enumeration and USB management process.
107 */
108 EVENT_HANDLER(USB_Connect)
109 {
110 #if !defined(INTERRUPT_CONTROL_ENDPOINT)
111 /* Start USB management task */
112 Scheduler_SetTaskMode(USB_USBTask, TASK_RUN);
113 #endif
114
115 /* Indicate USB enumerating */
116 UpdateStatus(Status_USBEnumerating);
117
118 /* Default to report protocol on connect */
119 UsingReportProtocol = true;
120 }
121
122 /** Event handler for the USB_Reset event. This fires when the USB interface is reset by the USB host, before the
123 * enumeration process begins, and enables the control endpoint interrupt so that control requests can be handled
124 * asynchronously when they arrive rather than when the control endpoint is polled manually.
125 */
126 EVENT_HANDLER(USB_Reset)
127 {
128 #if defined(INTERRUPT_CONTROL_ENDPOINT)
129 /* Select the control endpoint */
130 Endpoint_SelectEndpoint(ENDPOINT_CONTROLEP);
131
132 /* Enable the endpoint SETUP interrupt ISR for the control endpoint */
133 USB_INT_Enable(ENDPOINT_INT_SETUP);
134 #endif
135 }
136
137 /** Event handler for the USB_Disconnect event. This indicates that the device is no longer connected to a host via
138 * the status LEDs.
139 */
140 EVENT_HANDLER(USB_Disconnect)
141 {
142 /* Stop running keyboard reporting and USB management tasks */
143 #if !defined(INTERRUPT_DATA_ENDPOINT)
144 Scheduler_SetTaskMode(USB_Keyboard_Report, TASK_STOP);
145 #endif
146
147 #if !defined(INTERRUPT_CONTROL_ENDPOINT)
148 Scheduler_SetTaskMode(USB_USBTask, TASK_STOP);
149 #endif
150
151 /* Indicate USB not ready */
152 UpdateStatus(Status_USBNotReady);
153 }
154
155 /** Event handler for the USB_ConfigurationChanged event. This is fired when the host sets the current configuration
156 * of the USB device after enumeration, and configures the keyboard device endpoints.
157 */
158 EVENT_HANDLER(USB_ConfigurationChanged)
159 {
160 /* Setup Keyboard Keycode Report Endpoint */
161 Endpoint_ConfigureEndpoint(KEYBOARD_EPNUM, EP_TYPE_INTERRUPT,
162 ENDPOINT_DIR_IN, KEYBOARD_EPSIZE,
163 ENDPOINT_BANK_SINGLE);
164
165 #if defined(INTERRUPT_DATA_ENDPOINT)
166 /* Enable the endpoint IN interrupt ISR for the report endpoint */
167 USB_INT_Enable(ENDPOINT_INT_IN);
168 #endif
169
170 /* Setup Keyboard LED Report Endpoint */
171 Endpoint_ConfigureEndpoint(KEYBOARD_LEDS_EPNUM, EP_TYPE_INTERRUPT,
172 ENDPOINT_DIR_OUT, KEYBOARD_EPSIZE,
173 ENDPOINT_BANK_SINGLE);
174
175 #if defined(INTERRUPT_DATA_ENDPOINT)
176 /* Enable the endpoint OUT interrupt ISR for the LED report endpoint */
177 USB_INT_Enable(ENDPOINT_INT_OUT);
178 #endif
179
180 /* Indicate USB connected and ready */
181 UpdateStatus(Status_USBReady);
182
183 #if !defined(INTERRUPT_DATA_ENDPOINT)
184 /* Start running keyboard reporting task */
185 Scheduler_SetTaskMode(USB_Keyboard_Report, TASK_RUN);
186 #endif
187 }
188
189 /** Event handler for the USB_UnhandledControlPacket event. This is used to catch standard and class specific
190 * control requests that are not handled internally by the USB library (including the HID commands, which are
191 * all issued via the control endpoint), so that they can be handled appropriately for the application.
192 */
193 EVENT_HANDLER(USB_UnhandledControlPacket)
194 {
195 /* Handle HID Class specific requests */
196 switch (bRequest)
197 {
198 case REQ_GetReport:
199 if (bmRequestType == (REQDIR_DEVICETOHOST | REQTYPE_CLASS | REQREC_INTERFACE))
200 {
201 USB_KeyboardReport_Data_t KeyboardReportData;
202
203 /* Create the next keyboard report for transmission to the host */
204 CreateKeyboardReport(&KeyboardReportData);
205
206 /* Ignore report type and ID number value */
207 Endpoint_Discard_Word();
208
209 /* Ignore unused Interface number value */
210 Endpoint_Discard_Word();
211
212 /* Read in the number of bytes in the report to send to the host */
213 uint16_t wLength = Endpoint_Read_Word_LE();
214
215 /* If trying to send more bytes than exist to the host, clamp the value at the report size */
216 if (wLength > sizeof(KeyboardReportData))
217 wLength = sizeof(KeyboardReportData);
218
219 Endpoint_ClearControlSETUP();
220
221 /* Write the report data to the control endpoint */
222 Endpoint_Write_Control_Stream_LE(&KeyboardReportData, wLength);
223
224 /* Finalize the stream transfer to send the last packet or clear the host abort */
225 Endpoint_ClearControlOUT();
226 }
227
228 break;
229 case REQ_SetReport:
230 if (bmRequestType == (REQDIR_HOSTTODEVICE | REQTYPE_CLASS | REQREC_INTERFACE))
231 {
232 Endpoint_ClearControlSETUP();
233
234 /* Wait until the LED report has been sent by the host */
235 while (!(Endpoint_IsOUTReceived()));
236
237 /* Read in the LED report from the host */
238 uint8_t LEDStatus = Endpoint_Read_Byte();
239
240 /* Process the incoming LED report */
241 ProcessLEDReport(LEDStatus);
242
243 /* Clear the endpoint data */
244 Endpoint_ClearControlOUT();
245
246 /* Acknowledge status stage */
247 while (!(Endpoint_IsINReady()));
248 Endpoint_ClearControlIN();
249 }
250
251 break;
252 case REQ_GetProtocol:
253 if (bmRequestType == (REQDIR_DEVICETOHOST | REQTYPE_CLASS | REQREC_INTERFACE))
254 {
255 Endpoint_ClearControlSETUP();
256
257 /* Write the current protocol flag to the host */
258 Endpoint_Write_Byte(UsingReportProtocol);
259
260 /* Send the flag to the host */
261 Endpoint_ClearControlIN();
262
263 /* Acknowledge status stage */
264 while (!(Endpoint_IsOUTReceived()));
265 Endpoint_ClearControlOUT();
266 }
267
268 break;
269 case REQ_SetProtocol:
270 if (bmRequestType == (REQDIR_HOSTTODEVICE | REQTYPE_CLASS | REQREC_INTERFACE))
271 {
272 /* Read in the wValue parameter containing the new protocol mode */
273 uint16_t wValue = Endpoint_Read_Word_LE();
274
275 Endpoint_ClearControlSETUP();
276
277 /* Set or clear the flag depending on what the host indicates that the current Protocol should be */
278 UsingReportProtocol = (wValue != 0x0000);
279
280 /* Acknowledge status stage */
281 while (!(Endpoint_IsINReady()));
282 Endpoint_ClearControlIN();
283 }
284
285 break;
286 case REQ_SetIdle:
287 if (bmRequestType == (REQDIR_HOSTTODEVICE | REQTYPE_CLASS | REQREC_INTERFACE))
288 {
289 /* Read in the wValue parameter containing the idle period */
290 uint16_t wValue = Endpoint_Read_Word_LE();
291
292 Endpoint_ClearControlSETUP();
293
294 /* Get idle period in MSB */
295 IdleCount = (wValue >> 8);
296
297 /* Acknowledge status stage */
298 while (!(Endpoint_IsINReady()));
299 Endpoint_ClearControlIN();
300 }
301
302 break;
303 case REQ_GetIdle:
304 if (bmRequestType == (REQDIR_DEVICETOHOST | REQTYPE_CLASS | REQREC_INTERFACE))
305 {
306 Endpoint_ClearControlSETUP();
307
308 /* Write the current idle duration to the host */
309 Endpoint_Write_Byte(IdleCount);
310
311 /* Send the flag to the host */
312 Endpoint_ClearControlIN();
313
314 /* Acknowledge status stage */
315 while (!(Endpoint_IsOUTReceived()));
316 Endpoint_ClearControlOUT();
317 }
318
319 break;
320 }
321 }
322
323 /** ISR for the timer 0 compare vector. This ISR fires once each millisecond, and increments the
324 * scheduler elapsed idle period counter when the host has set an idle period.
325 */
326 ISR(TIMER0_COMPA_vect, ISR_BLOCK)
327 {
328 /* One millisecond has elapsed, decrement the idle time remaining counter if it has not already elapsed */
329 if (IdleMSRemaining)
330 IdleMSRemaining--;
331 }
332
333 /** Fills the given HID report data structure with the next HID report to send to the host.
334 *
335 * \param ReportData Pointer to a HID report data structure to be filled
336 */
337 void CreateKeyboardReport(USB_KeyboardReport_Data_t* ReportData)
338 {
339 uint8_t JoyStatus_LCL = Joystick_GetStatus();
340
341 /* Clear the report contents */
342 memset(ReportData, 0, sizeof(USB_KeyboardReport_Data_t));
343
344 if (JoyStatus_LCL & JOY_UP)
345 ReportData->KeyCode[0] = 0x04; // A
346 else if (JoyStatus_LCL & JOY_DOWN)
347 ReportData->KeyCode[0] = 0x05; // B
348
349 if (JoyStatus_LCL & JOY_LEFT)
350 ReportData->KeyCode[0] = 0x06; // C
351 else if (JoyStatus_LCL & JOY_RIGHT)
352 ReportData->KeyCode[0] = 0x07; // D
353
354 if (JoyStatus_LCL & JOY_PRESS)
355 ReportData->KeyCode[0] = 0x08; // E
356 }
357
358 /** Processes a received LED report, and updates the board LEDs states to match.
359 *
360 * \param LEDReport LED status report from the host
361 */
362 void ProcessLEDReport(uint8_t LEDReport)
363 {
364 uint8_t LEDMask = LEDS_LED2;
365
366 if (LEDReport & 0x01) // NUM Lock
367 LEDMask |= LEDS_LED1;
368
369 if (LEDReport & 0x02) // CAPS Lock
370 LEDMask |= LEDS_LED3;
371
372 if (LEDReport & 0x04) // SCROLL Lock
373 LEDMask |= LEDS_LED4;
374
375 /* Set the status LEDs to the current Keyboard LED status */
376 LEDs_SetAllLEDs(LEDMask);
377 }
378
379 /** Sends the next HID report to the host, via the keyboard data endpoint. */
380 static inline void SendNextReport(void)
381 {
382 static USB_KeyboardReport_Data_t PrevKeyboardReportData;
383 USB_KeyboardReport_Data_t KeyboardReportData;
384 bool SendReport = true;
385
386 /* Create the next keyboard report for transmission to the host */
387 CreateKeyboardReport(&KeyboardReportData);
388
389 /* Check if the idle period is set */
390 if (IdleCount)
391 {
392 /* Check if idle period has elapsed */
393 if (!(IdleMSRemaining))
394 {
395 /* Reset the idle time remaining counter, must multiply by 4 to get the duration in milliseconds */
396 IdleMSRemaining = (IdleCount << 2);
397 }
398 else
399 {
400 /* Idle period not elapsed, indicate that a report must not be sent unless the report has changed */
401 SendReport = (memcmp(&PrevKeyboardReportData, &KeyboardReportData, sizeof(USB_KeyboardReport_Data_t)) != 0);
402 }
403 }
404
405 /* Save the current report data for later comparison to check for changes */
406 PrevKeyboardReportData = KeyboardReportData;
407
408 /* Select the Keyboard Report Endpoint */
409 Endpoint_SelectEndpoint(KEYBOARD_EPNUM);
410
411 /* Check if Keyboard Endpoint Ready for Read/Write, and if we should send a report */
412 if (Endpoint_IsReadWriteAllowed() && SendReport)
413 {
414 /* Write Keyboard Report Data */
415 Endpoint_Write_Stream_LE(&KeyboardReportData, sizeof(KeyboardReportData));
416
417 /* Finalize the stream transfer to send the last packet */
418 Endpoint_ClearIN();
419 }
420 }
421
422 /** Reads the next LED status report from the host from the LED data endpoint, if one has been sent. */
423 static inline void ReceiveNextReport(void)
424 {
425 /* Select the Keyboard LED Report Endpoint */
426 Endpoint_SelectEndpoint(KEYBOARD_LEDS_EPNUM);
427
428 /* Check if Keyboard LED Endpoint contains a packet */
429 if (Endpoint_IsOUTReceived())
430 {
431 /* Check to see if the packet contains data */
432 if (Endpoint_IsReadWriteAllowed())
433 {
434 /* Read in the LED report from the host */
435 uint8_t LEDReport = Endpoint_Read_Byte();
436
437 /* Process the read LED report from the host */
438 ProcessLEDReport(LEDReport);
439 }
440
441 /* Handshake the OUT Endpoint - clear endpoint and ready for next report */
442 Endpoint_ClearOUT();
443 }
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 Keyboard_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 }