USBtoSerial.c 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254
  1. /*
  2. LUFA Library
  3. Copyright (C) Dean Camera, 2018.
  4. dean [at] fourwalledcubicle [dot] com
  5. www.lufa-lib.org
  6. */
  7. /*
  8. Copyright 2018 Dean Camera (dean [at] fourwalledcubicle [dot] com)
  9. Permission to use, copy, modify, distribute, and sell this
  10. software and its documentation for any purpose is hereby granted
  11. without fee, provided that the above copyright notice appear in
  12. all copies and that both that the copyright notice and this
  13. permission notice and warranty disclaimer appear in supporting
  14. documentation, and that the name of the author not be used in
  15. advertising or publicity pertaining to distribution of the
  16. software without specific, written prior permission.
  17. The author disclaims all warranties with regard to this
  18. software, including all implied warranties of merchantability
  19. and fitness. In no event shall the author be liable for any
  20. special, indirect or consequential damages or any damages
  21. whatsoever resulting from loss of use, data or profits, whether
  22. in an action of contract, negligence or other tortious action,
  23. arising out of or in connection with the use or performance of
  24. this software.
  25. */
  26. /** \file
  27. *
  28. * Main source file for the USBtoSerial project. This file contains the main tasks of
  29. * the project and is responsible for the initial application hardware configuration.
  30. */
  31. #include "USBtoSerial.h"
  32. /** Circular buffer to hold data from the host before it is sent to the device via the serial port. */
  33. static RingBuffer_t USBtoUSART_Buffer;
  34. /** Underlying data buffer for \ref USBtoUSART_Buffer, where the stored bytes are located. */
  35. static uint8_t USBtoUSART_Buffer_Data[128];
  36. /** Circular buffer to hold data from the serial port before it is sent to the host. */
  37. static RingBuffer_t USARTtoUSB_Buffer;
  38. /** Underlying data buffer for \ref USARTtoUSB_Buffer, where the stored bytes are located. */
  39. static uint8_t USARTtoUSB_Buffer_Data[128];
  40. /** LUFA CDC Class driver interface configuration and state information. This structure is
  41. * passed to all CDC Class driver functions, so that multiple instances of the same class
  42. * within a device can be differentiated from one another.
  43. */
  44. USB_ClassInfo_CDC_Device_t VirtualSerial_CDC_Interface =
  45. {
  46. .Config =
  47. {
  48. .ControlInterfaceNumber = INTERFACE_ID_CDC_CCI,
  49. .DataINEndpoint =
  50. {
  51. .Address = CDC_TX_EPADDR,
  52. .Size = CDC_TXRX_EPSIZE,
  53. .Banks = 1,
  54. },
  55. .DataOUTEndpoint =
  56. {
  57. .Address = CDC_RX_EPADDR,
  58. .Size = CDC_TXRX_EPSIZE,
  59. .Banks = 1,
  60. },
  61. .NotificationEndpoint =
  62. {
  63. .Address = CDC_NOTIFICATION_EPADDR,
  64. .Size = CDC_NOTIFICATION_EPSIZE,
  65. .Banks = 1,
  66. },
  67. },
  68. };
  69. /** Main program entry point. This routine contains the overall program flow, including initial
  70. * setup of all components and the main program loop.
  71. */
  72. int main(void)
  73. {
  74. SetupHardware();
  75. RingBuffer_InitBuffer(&USBtoUSART_Buffer, USBtoUSART_Buffer_Data, sizeof(USBtoUSART_Buffer_Data));
  76. RingBuffer_InitBuffer(&USARTtoUSB_Buffer, USARTtoUSB_Buffer_Data, sizeof(USARTtoUSB_Buffer_Data));
  77. LEDs_SetAllLEDs(LEDMASK_USB_NOTREADY);
  78. GlobalInterruptEnable();
  79. for (;;)
  80. {
  81. /* Only try to read in bytes from the CDC interface if the transmit buffer is not full */
  82. if (!(RingBuffer_IsFull(&USBtoUSART_Buffer)))
  83. {
  84. int16_t ReceivedByte = CDC_Device_ReceiveByte(&VirtualSerial_CDC_Interface);
  85. /* Store received byte into the USART transmit buffer */
  86. if (!(ReceivedByte < 0))
  87. RingBuffer_Insert(&USBtoUSART_Buffer, ReceivedByte);
  88. }
  89. uint16_t BufferCount = RingBuffer_GetCount(&USARTtoUSB_Buffer);
  90. if (BufferCount)
  91. {
  92. Endpoint_SelectEndpoint(VirtualSerial_CDC_Interface.Config.DataINEndpoint.Address);
  93. /* Check if a packet is already enqueued to the host - if so, we shouldn't try to send more data
  94. * until it completes as there is a chance nothing is listening and a lengthy timeout could occur */
  95. if (Endpoint_IsINReady())
  96. {
  97. /* Never send more than one bank size less one byte to the host at a time, so that we don't block
  98. * while a Zero Length Packet (ZLP) to terminate the transfer is sent if the host isn't listening */
  99. uint8_t BytesToSend = MIN(BufferCount, (CDC_TXRX_EPSIZE - 1));
  100. /* Read bytes from the USART receive buffer into the USB IN endpoint */
  101. while (BytesToSend--)
  102. {
  103. /* Try to send the next byte of data to the host, abort if there is an error without dequeuing */
  104. if (CDC_Device_SendByte(&VirtualSerial_CDC_Interface,
  105. RingBuffer_Peek(&USARTtoUSB_Buffer)) != ENDPOINT_READYWAIT_NoError)
  106. {
  107. break;
  108. }
  109. /* Dequeue the already sent byte from the buffer now we have confirmed that no transmission error occurred */
  110. RingBuffer_Remove(&USARTtoUSB_Buffer);
  111. }
  112. }
  113. }
  114. /* Load the next byte from the USART transmit buffer into the USART if transmit buffer space is available */
  115. if (Serial_IsSendReady() && !(RingBuffer_IsEmpty(&USBtoUSART_Buffer)))
  116. Serial_SendByte(RingBuffer_Remove(&USBtoUSART_Buffer));
  117. CDC_Device_USBTask(&VirtualSerial_CDC_Interface);
  118. USB_USBTask();
  119. }
  120. }
  121. /** Configures the board hardware and chip peripherals for the demo's functionality. */
  122. void SetupHardware(void)
  123. {
  124. #if (ARCH == ARCH_AVR8)
  125. /* Disable watchdog if enabled by bootloader/fuses */
  126. MCUSR &= ~(1 << WDRF);
  127. wdt_disable();
  128. /* Disable clock division */
  129. clock_prescale_set(clock_div_1);
  130. #endif
  131. /* Hardware Initialization */
  132. LEDs_Init();
  133. USB_Init();
  134. }
  135. /** Event handler for the library USB Connection event. */
  136. void EVENT_USB_Device_Connect(void)
  137. {
  138. LEDs_SetAllLEDs(LEDMASK_USB_ENUMERATING);
  139. }
  140. /** Event handler for the library USB Disconnection event. */
  141. void EVENT_USB_Device_Disconnect(void)
  142. {
  143. LEDs_SetAllLEDs(LEDMASK_USB_NOTREADY);
  144. }
  145. /** Event handler for the library USB Configuration Changed event. */
  146. void EVENT_USB_Device_ConfigurationChanged(void)
  147. {
  148. bool ConfigSuccess = true;
  149. ConfigSuccess &= CDC_Device_ConfigureEndpoints(&VirtualSerial_CDC_Interface);
  150. LEDs_SetAllLEDs(ConfigSuccess ? LEDMASK_USB_READY : LEDMASK_USB_ERROR);
  151. }
  152. /** Event handler for the library USB Control Request reception event. */
  153. void EVENT_USB_Device_ControlRequest(void)
  154. {
  155. CDC_Device_ProcessControlRequest(&VirtualSerial_CDC_Interface);
  156. }
  157. /** ISR to manage the reception of data from the serial port, placing received bytes into a circular buffer
  158. * for later transmission to the host.
  159. */
  160. ISR(USART1_RX_vect, ISR_BLOCK)
  161. {
  162. uint8_t ReceivedByte = UDR1;
  163. if ((USB_DeviceState == DEVICE_STATE_Configured) && !(RingBuffer_IsFull(&USARTtoUSB_Buffer)))
  164. RingBuffer_Insert(&USARTtoUSB_Buffer, ReceivedByte);
  165. }
  166. /** Event handler for the CDC Class driver Line Encoding Changed event.
  167. *
  168. * \param[in] CDCInterfaceInfo Pointer to the CDC class interface configuration structure being referenced
  169. */
  170. void EVENT_CDC_Device_LineEncodingChanged(USB_ClassInfo_CDC_Device_t* const CDCInterfaceInfo)
  171. {
  172. uint8_t ConfigMask = 0;
  173. switch (CDCInterfaceInfo->State.LineEncoding.ParityType)
  174. {
  175. case CDC_PARITY_Odd:
  176. ConfigMask = ((1 << UPM11) | (1 << UPM10));
  177. break;
  178. case CDC_PARITY_Even:
  179. ConfigMask = (1 << UPM11);
  180. break;
  181. }
  182. if (CDCInterfaceInfo->State.LineEncoding.CharFormat == CDC_LINEENCODING_TwoStopBits)
  183. ConfigMask |= (1 << USBS1);
  184. switch (CDCInterfaceInfo->State.LineEncoding.DataBits)
  185. {
  186. case 6:
  187. ConfigMask |= (1 << UCSZ10);
  188. break;
  189. case 7:
  190. ConfigMask |= (1 << UCSZ11);
  191. break;
  192. case 8:
  193. ConfigMask |= ((1 << UCSZ11) | (1 << UCSZ10));
  194. break;
  195. }
  196. /* Keep the TX line held high (idle) while the USART is reconfigured */
  197. PORTD |= (1 << 3);
  198. /* Must turn off USART before reconfiguring it, otherwise incorrect operation may occur */
  199. UCSR1B = 0;
  200. UCSR1A = 0;
  201. UCSR1C = 0;
  202. /* Set the new baud rate before configuring the USART */
  203. UBRR1 = SERIAL_2X_UBBRVAL(CDCInterfaceInfo->State.LineEncoding.BaudRateBPS);
  204. /* Reconfigure the USART in double speed mode for a wider baud rate range at the expense of accuracy */
  205. UCSR1C = ConfigMask;
  206. UCSR1A = (1 << U2X1);
  207. UCSR1B = ((1 << RXCIE1) | (1 << TXEN1) | (1 << RXEN1));
  208. /* Release the TX line after the USART has been reconfigured */
  209. PORTD &= ~(1 << 3);
  210. }