Keyboard firmwares for Atmel AVR and Cortex-M
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

Keyboard.c 12KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383
  1. /*
  2. LUFA Library
  3. Copyright (C) Dean Camera, 2014.
  4. dean [at] fourwalledcubicle [dot] com
  5. www.lufa-lib.org
  6. */
  7. /*
  8. Copyright 2014 Dean Camera (dean [at] fourwalledcubicle [dot] com)
  9. Copyright 2010 Denver Gingerich (denver [at] ossguy [dot] com)
  10. Permission to use, copy, modify, distribute, and sell this
  11. software and its documentation for any purpose is hereby granted
  12. without fee, provided that the above copyright notice appear in
  13. all copies and that both that the copyright notice and this
  14. permission notice and warranty disclaimer appear in supporting
  15. documentation, and that the name of the author not be used in
  16. advertising or publicity pertaining to distribution of the
  17. software without specific, written prior permission.
  18. The author disclaims all warranties with regard to this
  19. software, including all implied warranties of merchantability
  20. and fitness. In no event shall the author be liable for any
  21. special, indirect or consequential damages or any damages
  22. whatsoever resulting from loss of use, data or profits, whether
  23. in an action of contract, negligence or other tortious action,
  24. arising out of or in connection with the use or performance of
  25. this software.
  26. */
  27. /** \file
  28. *
  29. * Main source file for the Keyboard demo. This file contains the main tasks of the demo and
  30. * is responsible for the initial application hardware configuration.
  31. */
  32. #include "Keyboard.h"
  33. /** Indicates what report mode the host has requested, true for normal HID reporting mode, \c false for special boot
  34. * protocol reporting mode.
  35. */
  36. static bool UsingReportProtocol = true;
  37. /** Current Idle period. This is set by the host via a Set Idle HID class request to silence the device's reports
  38. * for either the entire idle duration, or until the report status changes (e.g. the user presses a key).
  39. */
  40. static uint16_t IdleCount = 500;
  41. /** Current Idle period remaining. When the IdleCount value is set, this tracks the remaining number of idle
  42. * milliseconds. This is separate to the IdleCount timer and is incremented and compared as the host may request
  43. * the current idle period via a Get Idle HID class request, thus its value must be preserved.
  44. */
  45. static uint16_t IdleMSRemaining = 0;
  46. /** Main program entry point. This routine configures the hardware required by the application, then
  47. * enters a loop to run the application tasks in sequence.
  48. */
  49. int main(void)
  50. {
  51. SetupHardware();
  52. LEDs_SetAllLEDs(LEDMASK_USB_NOTREADY);
  53. GlobalInterruptEnable();
  54. for (;;)
  55. {
  56. HID_Task();
  57. USB_USBTask();
  58. }
  59. }
  60. /** Configures the board hardware and chip peripherals for the demo's functionality. */
  61. void SetupHardware(void)
  62. {
  63. #if (ARCH == ARCH_AVR8)
  64. /* Disable watchdog if enabled by bootloader/fuses */
  65. MCUSR &= ~(1 << WDRF);
  66. wdt_disable();
  67. /* Disable clock division */
  68. clock_prescale_set(clock_div_1);
  69. #elif (ARCH == ARCH_XMEGA)
  70. /* Start the PLL to multiply the 2MHz RC oscillator to 32MHz and switch the CPU core to run from it */
  71. XMEGACLK_StartPLL(CLOCK_SRC_INT_RC2MHZ, 2000000, F_CPU);
  72. XMEGACLK_SetCPUClockSource(CLOCK_SRC_PLL);
  73. /* Start the 32MHz internal RC oscillator and start the DFLL to increase it to 48MHz using the USB SOF as a reference */
  74. XMEGACLK_StartInternalOscillator(CLOCK_SRC_INT_RC32MHZ);
  75. XMEGACLK_StartDFLL(CLOCK_SRC_INT_RC32MHZ, DFLL_REF_INT_USBSOF, F_USB);
  76. PMIC.CTRL = PMIC_LOLVLEN_bm | PMIC_MEDLVLEN_bm | PMIC_HILVLEN_bm;
  77. #endif
  78. /* Hardware Initialization */
  79. Joystick_Init();
  80. LEDs_Init();
  81. USB_Init();
  82. Buttons_Init();
  83. }
  84. /** Event handler for the USB_Connect event. This indicates that the device is enumerating via the status LEDs and
  85. * starts the library USB task to begin the enumeration and USB management process.
  86. */
  87. void EVENT_USB_Device_Connect(void)
  88. {
  89. /* Indicate USB enumerating */
  90. LEDs_SetAllLEDs(LEDMASK_USB_ENUMERATING);
  91. /* Default to report protocol on connect */
  92. UsingReportProtocol = true;
  93. }
  94. /** Event handler for the USB_Disconnect event. This indicates that the device is no longer connected to a host via
  95. * the status LEDs.
  96. */
  97. void EVENT_USB_Device_Disconnect(void)
  98. {
  99. /* Indicate USB not ready */
  100. LEDs_SetAllLEDs(LEDMASK_USB_NOTREADY);
  101. }
  102. /** Event handler for the USB_ConfigurationChanged event. This is fired when the host sets the current configuration
  103. * of the USB device after enumeration, and configures the keyboard device endpoints.
  104. */
  105. void EVENT_USB_Device_ConfigurationChanged(void)
  106. {
  107. bool ConfigSuccess = true;
  108. /* Setup HID Report Endpoints */
  109. ConfigSuccess &= Endpoint_ConfigureEndpoint(KEYBOARD_IN_EPADDR, EP_TYPE_INTERRUPT, KEYBOARD_EPSIZE, 1);
  110. ConfigSuccess &= Endpoint_ConfigureEndpoint(KEYBOARD_OUT_EPADDR, EP_TYPE_INTERRUPT, KEYBOARD_EPSIZE, 1);
  111. /* Turn on Start-of-Frame events for tracking HID report period expiry */
  112. USB_Device_EnableSOFEvents();
  113. /* Indicate endpoint configuration success or failure */
  114. LEDs_SetAllLEDs(ConfigSuccess ? LEDMASK_USB_READY : LEDMASK_USB_ERROR);
  115. }
  116. /** Event handler for the USB_ControlRequest event. This is used to catch and process control requests sent to
  117. * the device from the USB host before passing along unhandled control requests to the library for processing
  118. * internally.
  119. */
  120. void EVENT_USB_Device_ControlRequest(void)
  121. {
  122. /* Handle HID Class specific requests */
  123. switch (USB_ControlRequest.bRequest)
  124. {
  125. case HID_REQ_GetReport:
  126. if (USB_ControlRequest.bmRequestType == (REQDIR_DEVICETOHOST | REQTYPE_CLASS | REQREC_INTERFACE))
  127. {
  128. USB_KeyboardReport_Data_t KeyboardReportData;
  129. /* Create the next keyboard report for transmission to the host */
  130. CreateKeyboardReport(&KeyboardReportData);
  131. Endpoint_ClearSETUP();
  132. /* Write the report data to the control endpoint */
  133. Endpoint_Write_Control_Stream_LE(&KeyboardReportData, sizeof(KeyboardReportData));
  134. Endpoint_ClearOUT();
  135. }
  136. break;
  137. case HID_REQ_SetReport:
  138. if (USB_ControlRequest.bmRequestType == (REQDIR_HOSTTODEVICE | REQTYPE_CLASS | REQREC_INTERFACE))
  139. {
  140. Endpoint_ClearSETUP();
  141. /* Wait until the LED report has been sent by the host */
  142. while (!(Endpoint_IsOUTReceived()))
  143. {
  144. if (USB_DeviceState == DEVICE_STATE_Unattached)
  145. return;
  146. }
  147. /* Read in the LED report from the host */
  148. uint8_t LEDStatus = Endpoint_Read_8();
  149. Endpoint_ClearOUT();
  150. Endpoint_ClearStatusStage();
  151. /* Process the incoming LED report */
  152. ProcessLEDReport(LEDStatus);
  153. }
  154. break;
  155. case HID_REQ_GetProtocol:
  156. if (USB_ControlRequest.bmRequestType == (REQDIR_DEVICETOHOST | REQTYPE_CLASS | REQREC_INTERFACE))
  157. {
  158. Endpoint_ClearSETUP();
  159. /* Write the current protocol flag to the host */
  160. Endpoint_Write_8(UsingReportProtocol);
  161. Endpoint_ClearIN();
  162. Endpoint_ClearStatusStage();
  163. }
  164. break;
  165. case HID_REQ_SetProtocol:
  166. if (USB_ControlRequest.bmRequestType == (REQDIR_HOSTTODEVICE | REQTYPE_CLASS | REQREC_INTERFACE))
  167. {
  168. Endpoint_ClearSETUP();
  169. Endpoint_ClearStatusStage();
  170. /* Set or clear the flag depending on what the host indicates that the current Protocol should be */
  171. UsingReportProtocol = (USB_ControlRequest.wValue != 0);
  172. }
  173. break;
  174. case HID_REQ_SetIdle:
  175. if (USB_ControlRequest.bmRequestType == (REQDIR_HOSTTODEVICE | REQTYPE_CLASS | REQREC_INTERFACE))
  176. {
  177. Endpoint_ClearSETUP();
  178. Endpoint_ClearStatusStage();
  179. /* Get idle period in MSB, IdleCount must be multiplied by 4 to get number of milliseconds */
  180. IdleCount = ((USB_ControlRequest.wValue & 0xFF00) >> 6);
  181. }
  182. break;
  183. case HID_REQ_GetIdle:
  184. if (USB_ControlRequest.bmRequestType == (REQDIR_DEVICETOHOST | REQTYPE_CLASS | REQREC_INTERFACE))
  185. {
  186. Endpoint_ClearSETUP();
  187. /* Write the current idle duration to the host, must be divided by 4 before sent to host */
  188. Endpoint_Write_8(IdleCount >> 2);
  189. Endpoint_ClearIN();
  190. Endpoint_ClearStatusStage();
  191. }
  192. break;
  193. }
  194. }
  195. /** Event handler for the USB device Start Of Frame event. */
  196. void EVENT_USB_Device_StartOfFrame(void)
  197. {
  198. /* One millisecond has elapsed, decrement the idle time remaining counter if it has not already elapsed */
  199. if (IdleMSRemaining)
  200. IdleMSRemaining--;
  201. }
  202. /** Fills the given HID report data structure with the next HID report to send to the host.
  203. *
  204. * \param[out] ReportData Pointer to a HID report data structure to be filled
  205. */
  206. void CreateKeyboardReport(USB_KeyboardReport_Data_t* const ReportData)
  207. {
  208. uint8_t JoyStatus_LCL = Joystick_GetStatus();
  209. uint8_t ButtonStatus_LCL = Buttons_GetStatus();
  210. uint8_t UsedKeyCodes = 0;
  211. /* Clear the report contents */
  212. memset(ReportData, 0, sizeof(USB_KeyboardReport_Data_t));
  213. /* Make sent key uppercase by indicating that the left shift key is pressed */
  214. ReportData->Modifier = HID_KEYBOARD_MODIFIER_LEFTSHIFT;
  215. if (JoyStatus_LCL & JOY_UP)
  216. ReportData->KeyCode[UsedKeyCodes++] = HID_KEYBOARD_SC_A;
  217. else if (JoyStatus_LCL & JOY_DOWN)
  218. ReportData->KeyCode[UsedKeyCodes++] = HID_KEYBOARD_SC_B;
  219. if (JoyStatus_LCL & JOY_LEFT)
  220. ReportData->KeyCode[UsedKeyCodes++] = HID_KEYBOARD_SC_C;
  221. else if (JoyStatus_LCL & JOY_RIGHT)
  222. ReportData->KeyCode[UsedKeyCodes++] = HID_KEYBOARD_SC_D;
  223. if (JoyStatus_LCL & JOY_PRESS)
  224. ReportData->KeyCode[UsedKeyCodes++] = HID_KEYBOARD_SC_E;
  225. if (ButtonStatus_LCL & BUTTONS_BUTTON1)
  226. ReportData->KeyCode[UsedKeyCodes++] = HID_KEYBOARD_SC_F;
  227. }
  228. /** Processes a received LED report, and updates the board LEDs states to match.
  229. *
  230. * \param[in] LEDReport LED status report from the host
  231. */
  232. void ProcessLEDReport(const uint8_t LEDReport)
  233. {
  234. uint8_t LEDMask = LEDS_LED2;
  235. if (LEDReport & HID_KEYBOARD_LED_NUMLOCK)
  236. LEDMask |= LEDS_LED1;
  237. if (LEDReport & HID_KEYBOARD_LED_CAPSLOCK)
  238. LEDMask |= LEDS_LED3;
  239. if (LEDReport & HID_KEYBOARD_LED_SCROLLLOCK)
  240. LEDMask |= LEDS_LED4;
  241. /* Set the status LEDs to the current Keyboard LED status */
  242. LEDs_SetAllLEDs(LEDMask);
  243. }
  244. /** Sends the next HID report to the host, via the keyboard data endpoint. */
  245. void SendNextReport(void)
  246. {
  247. static USB_KeyboardReport_Data_t PrevKeyboardReportData;
  248. USB_KeyboardReport_Data_t KeyboardReportData;
  249. bool SendReport = false;
  250. /* Create the next keyboard report for transmission to the host */
  251. CreateKeyboardReport(&KeyboardReportData);
  252. /* Check if the idle period is set and has elapsed */
  253. if (IdleCount && (!(IdleMSRemaining)))
  254. {
  255. /* Reset the idle time remaining counter */
  256. IdleMSRemaining = IdleCount;
  257. /* Idle period is set and has elapsed, must send a report to the host */
  258. SendReport = true;
  259. }
  260. else
  261. {
  262. /* Check to see if the report data has changed - if so a report MUST be sent */
  263. SendReport = (memcmp(&PrevKeyboardReportData, &KeyboardReportData, sizeof(USB_KeyboardReport_Data_t)) != 0);
  264. }
  265. /* Select the Keyboard Report Endpoint */
  266. Endpoint_SelectEndpoint(KEYBOARD_IN_EPADDR);
  267. /* Check if Keyboard Endpoint Ready for Read/Write and if we should send a new report */
  268. if (Endpoint_IsReadWriteAllowed() && SendReport)
  269. {
  270. /* Save the current report data for later comparison to check for changes */
  271. PrevKeyboardReportData = KeyboardReportData;
  272. /* Write Keyboard Report Data */
  273. Endpoint_Write_Stream_LE(&KeyboardReportData, sizeof(KeyboardReportData), NULL);
  274. /* Finalize the stream transfer to send the last packet */
  275. Endpoint_ClearIN();
  276. }
  277. }
  278. /** Reads the next LED status report from the host from the LED data endpoint, if one has been sent. */
  279. void ReceiveNextReport(void)
  280. {
  281. /* Select the Keyboard LED Report Endpoint */
  282. Endpoint_SelectEndpoint(KEYBOARD_OUT_EPADDR);
  283. /* Check if Keyboard LED Endpoint contains a packet */
  284. if (Endpoint_IsOUTReceived())
  285. {
  286. /* Check to see if the packet contains data */
  287. if (Endpoint_IsReadWriteAllowed())
  288. {
  289. /* Read in the LED report from the host */
  290. uint8_t LEDReport = Endpoint_Read_8();
  291. /* Process the read LED report from the host */
  292. ProcessLEDReport(LEDReport);
  293. }
  294. /* Handshake the OUT Endpoint - clear endpoint and ready for next report */
  295. Endpoint_ClearOUT();
  296. }
  297. }
  298. /** Function to manage HID report generation and transmission to the host, when in report mode. */
  299. void HID_Task(void)
  300. {
  301. /* Device must be connected and configured for the task to run */
  302. if (USB_DeviceState != DEVICE_STATE_Configured)
  303. return;
  304. /* Send the next keypress report to the host */
  305. SendNextReport();
  306. /* Process the LED report sent from the host */
  307. ReceiveNextReport();
  308. }