Better fix for LowLevel CDC demo issue where sending data before the line encoding...
[pub/USBasp.git] / Demos / Device / LowLevel / USBtoSerial / USBtoSerial.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 Dean Camera (dean [at] fourwalledcubicle [dot] com)
11
12 Permission to use, copy, modify, and distribute this software
13 and its documentation for any purpose and without fee is hereby
14 granted, provided that the above copyright notice appear in all
15 copies and that both that the copyright notice and this
16 permission notice and warranty disclaimer appear in supporting
17 documentation, and that the name of the author not be used in
18 advertising or publicity pertaining to distribution of the
19 software without specific, written prior permission.
20
21 The author disclaim all warranties with regard to this
22 software, including all implied warranties of merchantability
23 and fitness. In no event shall the author be liable for any
24 special, indirect or consequential damages or any damages
25 whatsoever resulting from loss of use, data or profits, whether
26 in an action of contract, negligence or other tortious action,
27 arising out of or in connection with the use or performance of
28 this software.
29 */
30
31 #include "USBtoSerial.h"
32
33 /* Globals: */
34 /** Contains the current baud rate and other settings of the virtual serial port.
35 *
36 * These values are set by the host via a class-specific request, and the physical USART should be reconfigured to match the
37 * new settings each time they are changed by the host.
38 */
39 CDC_Line_Coding_t LineEncoding = { .BaudRateBPS = 0,
40 .CharFormat = OneStopBit,
41 .ParityType = Parity_None,
42 .DataBits = 8 };
43
44 /** Ring (circular) buffer to hold the RX data - data from the host to the attached device on the serial port. */
45 RingBuff_t Rx_Buffer;
46
47 /** Ring (circular) buffer to hold the TX data - data from the attached device on the serial port to the host. */
48 RingBuff_t Tx_Buffer;
49
50 /** Flag to indicate if the USART is currently transmitting data from the Rx_Buffer circular buffer. */
51 volatile bool Transmitting = false;
52
53 /** Main program entry point. This routine configures the hardware required by the application, then
54 * starts the scheduler to run the application tasks.
55 */
56 int main(void)
57 {
58 SetupHardware();
59
60 /* Ring buffer Initialization */
61 Buffer_Initialize(&Rx_Buffer);
62 Buffer_Initialize(&Tx_Buffer);
63
64 LEDs_SetAllLEDs(LEDMASK_USB_NOTREADY);
65
66 for (;;)
67 {
68 CDC_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 LEDs_Init();
85 ReconfigureUSART();
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_Connect(void)
93 {
94 /* Indicate USB enumerating */
95 LEDs_SetAllLEDs(LEDMASK_USB_ENUMERATING);
96 }
97
98 /** Event handler for the USB_Disconnect event. This indicates that the device is no longer connected to a host via
99 * the status LEDs and stops the USB management and CDC management tasks.
100 */
101 void EVENT_USB_Disconnect(void)
102 {
103 /* Reset Tx and Rx buffers, device disconnected */
104 Buffer_Initialize(&Rx_Buffer);
105 Buffer_Initialize(&Tx_Buffer);
106
107 /* Indicate USB not ready */
108 LEDs_SetAllLEDs(LEDMASK_USB_NOTREADY);
109 }
110
111 /** Event handler for the USB_ConfigurationChanged event. This is fired when the host set the current configuration
112 * of the USB device after enumeration - the device endpoints are configured and the CDC management task started.
113 */
114 void EVENT_USB_ConfigurationChanged(void)
115 {
116 /* Indicate USB connected and ready */
117 LEDs_SetAllLEDs(LEDMASK_USB_READY);
118
119 /* Setup CDC Notification, Rx and Tx Endpoints */
120 if (!(Endpoint_ConfigureEndpoint(CDC_NOTIFICATION_EPNUM, EP_TYPE_INTERRUPT,
121 ENDPOINT_DIR_IN, CDC_NOTIFICATION_EPSIZE,
122 ENDPOINT_BANK_SINGLE)))
123 {
124 LEDs_SetAllLEDs(LEDMASK_USB_ERROR);
125 }
126
127 if (!(Endpoint_ConfigureEndpoint(CDC_TX_EPNUM, EP_TYPE_BULK,
128 ENDPOINT_DIR_IN, CDC_TXRX_EPSIZE,
129 ENDPOINT_BANK_SINGLE)))
130 {
131 LEDs_SetAllLEDs(LEDMASK_USB_ERROR);
132 }
133
134 if (!(Endpoint_ConfigureEndpoint(CDC_RX_EPNUM, EP_TYPE_BULK,
135 ENDPOINT_DIR_OUT, CDC_TXRX_EPSIZE,
136 ENDPOINT_BANK_SINGLE)))
137 {
138 LEDs_SetAllLEDs(LEDMASK_USB_ERROR);
139 }
140 }
141
142 /** Event handler for the USB_UnhandledControlPacket event. This is used to catch standard and class specific
143 * control requests that are not handled internally by the USB library (including the CDC control commands,
144 * which are all issued via the control endpoint), so that they can be handled appropriately for the application.
145 */
146 void EVENT_USB_UnhandledControlPacket(void)
147 {
148 /* Process CDC specific control requests */
149 switch (USB_ControlRequest.bRequest)
150 {
151 case REQ_GetLineEncoding:
152 if (USB_ControlRequest.bmRequestType == (REQDIR_DEVICETOHOST | REQTYPE_CLASS | REQREC_INTERFACE))
153 {
154 /* Acknowledge the SETUP packet, ready for data transfer */
155 Endpoint_ClearSETUP();
156
157 /* Write the line coding data to the control endpoint */
158 Endpoint_Write_Control_Stream_LE(&LineEncoding, sizeof(LineEncoding));
159
160 /* Finalize the stream transfer to send the last packet or clear the host abort */
161 Endpoint_ClearOUT();
162 }
163
164 break;
165 case REQ_SetLineEncoding:
166 if (USB_ControlRequest.bmRequestType == (REQDIR_HOSTTODEVICE | REQTYPE_CLASS | REQREC_INTERFACE))
167 {
168 /* Acknowledge the SETUP packet, ready for data transfer */
169 Endpoint_ClearSETUP();
170
171 /* Read the line coding data in from the host into the global struct */
172 Endpoint_Read_Control_Stream_LE(&LineEncoding, sizeof(LineEncoding));
173
174 /* Finalize the stream transfer to clear the last packet from the host */
175 Endpoint_ClearIN();
176
177 /* Reconfigure the USART with the new settings */
178 ReconfigureUSART();
179 }
180
181 break;
182 case REQ_SetControlLineState:
183 if (USB_ControlRequest.bmRequestType == (REQDIR_HOSTTODEVICE | REQTYPE_CLASS | REQREC_INTERFACE))
184 {
185 /* Acknowledge the SETUP packet, ready for data transfer */
186 Endpoint_ClearSETUP();
187
188 /* NOTE: Here you can read in the line state mask from the host, to get the current state of the output handshake
189 lines. The mask is read in from the wValue parameter in USB_ControlRequest, and can be masked against the
190 CONTROL_LINE_OUT_* masks to determine the RTS and DTR line states using the following code:
191 */
192
193 Endpoint_ClearStatusStage();
194 }
195
196 break;
197 }
198 }
199
200 /** Task to manage CDC data transmission and reception to and from the host, from and to the physical USART. */
201 void CDC_Task(void)
202 {
203 /* Device must be connected and configured for the task to run */
204 if (USB_DeviceState != DEVICE_STATE_Configured)
205 return;
206
207 #if 0
208 /* NOTE: Here you can use the notification endpoint to send back line state changes to the host, for the special RS-232
209 handshake signal lines (and some error states), via the CONTROL_LINE_IN_* masks and the following code:
210 */
211
212 USB_Notification_Header_t Notification = (USB_Notification_Header_t)
213 {
214 .NotificationType = (REQDIR_DEVICETOHOST | REQTYPE_CLASS | REQREC_INTERFACE),
215 .Notification = NOTIF_SerialState,
216 .wValue = 0,
217 .wIndex = 0,
218 .wLength = sizeof(uint16_t),
219 };
220
221 uint16_t LineStateMask;
222
223 // Set LineStateMask here to a mask of CONTROL_LINE_IN_* masks to set the input handshake line states to send to the host
224
225 Endpoint_SelectEndpoint(CDC_NOTIFICATION_EPNUM);
226 Endpoint_Write_Stream_LE(&Notification, sizeof(Notification));
227 Endpoint_Write_Stream_LE(&LineStateMask, sizeof(LineStateMask));
228 Endpoint_ClearIN();
229 #endif
230
231 /* Select the Serial Rx Endpoint */
232 Endpoint_SelectEndpoint(CDC_RX_EPNUM);
233
234 /* Check to see if a packet has been received from the host */
235 if (Endpoint_IsOUTReceived())
236 {
237 /* Read the bytes in from the endpoint into the buffer while space is available */
238 while (Endpoint_BytesInEndpoint() && (Rx_Buffer.Elements != BUFF_STATICSIZE))
239 {
240 /* Store each character from the endpoint */
241 Buffer_StoreElement(&Rx_Buffer, Endpoint_Read_Byte());
242 }
243
244 /* Check to see if all bytes in the current packet have been read */
245 if (!(Endpoint_BytesInEndpoint()))
246 {
247 /* Clear the endpoint buffer */
248 Endpoint_ClearOUT();
249 }
250 }
251
252 /* Check if Rx buffer contains data - if so, send it */
253 if (Rx_Buffer.Elements)
254 Serial_TxByte(Buffer_GetElement(&Rx_Buffer));
255
256 /* Select the Serial Tx Endpoint */
257 Endpoint_SelectEndpoint(CDC_TX_EPNUM);
258
259 /* Check if the Tx buffer contains anything to be sent to the host */
260 if ((Tx_Buffer.Elements) && LineEncoding.BaudRateBPS)
261 {
262 /* Wait until Serial Tx Endpoint Ready for Read/Write */
263 while (!(Endpoint_IsReadWriteAllowed()))
264 {
265 if (USB_DeviceState == DEVICE_STATE_Unattached)
266 return;
267 }
268
269 /* Write the bytes from the buffer to the endpoint while space is available */
270 while (Tx_Buffer.Elements && Endpoint_IsReadWriteAllowed())
271 {
272 /* Write each byte retreived from the buffer to the endpoint */
273 Endpoint_Write_Byte(Buffer_GetElement(&Tx_Buffer));
274 }
275
276 /* Remember if the packet to send completely fills the endpoint */
277 bool IsFull = (Endpoint_BytesInEndpoint() == CDC_TXRX_EPSIZE);
278
279 /* Send the data */
280 Endpoint_ClearIN();
281
282 /* If no more data to send and the last packet filled the endpoint, send an empty packet to release
283 * the buffer on the receiver (otherwise all data will be cached until a non-full packet is received) */
284 if (IsFull && !(Tx_Buffer.Elements))
285 {
286 /* Wait until Serial Tx Endpoint Ready for Read/Write */
287 while (!(Endpoint_IsReadWriteAllowed()))
288 {
289 if (USB_DeviceState == DEVICE_STATE_Unattached)
290 return;
291 }
292
293 /* Send an empty packet to terminate the transfer */
294 Endpoint_ClearIN();
295 }
296 }
297 }
298
299 /** ISR to handle the USART receive complete interrupt, fired each time the USART has received a character. This stores the received
300 * character into the Tx_Buffer circular buffer for later transmission to the host.
301 */
302 ISR(USART1_RX_vect, ISR_BLOCK)
303 {
304 /* Only store received characters if the USB interface is connected */
305 if ((USB_DeviceState != DEVICE_STATE_Configured) && LineEncoding.BaudRateBPS)
306 Buffer_StoreElement(&Tx_Buffer, UDR1);
307 }
308
309 /** Reconfigures the USART to match the current serial port settings issued by the host as closely as possible. */
310 void ReconfigureUSART(void)
311 {
312 uint8_t ConfigMask = 0;
313
314 /* Determine parity - non odd/even parity mode defaults to no parity */
315 if (LineEncoding.ParityType == Parity_Odd)
316 ConfigMask = ((1 << UPM11) | (1 << UPM10));
317 else if (LineEncoding.ParityType == Parity_Even)
318 ConfigMask = (1 << UPM11);
319
320 /* Determine stop bits - 1.5 stop bits is set as 1 stop bit due to hardware limitations */
321 if (LineEncoding.CharFormat == TwoStopBits)
322 ConfigMask |= (1 << USBS1);
323
324 /* Determine data size - 5, 6, 7, or 8 bits are supported */
325 if (LineEncoding.DataBits == 6)
326 ConfigMask |= (1 << UCSZ10);
327 else if (LineEncoding.DataBits == 7)
328 ConfigMask |= (1 << UCSZ11);
329 else if (LineEncoding.DataBits == 8)
330 ConfigMask |= ((1 << UCSZ11) | (1 << UCSZ10));
331
332 /* Enable double speed, gives better error percentages at 8MHz */
333 UCSR1A = (1 << U2X1);
334
335 /* Enable transmit and receive modules and interrupts */
336 UCSR1B = ((1 << RXCIE1) | (1 << TXEN1) | (1 << RXEN1));
337
338 /* Set the USART mode to the mask generated by the Line Coding options */
339 UCSR1C = ConfigMask;
340
341 /* Set the USART baud rate register to the desired baud rate value */
342 UBRR1 = SERIAL_2X_UBBRVAL((uint16_t)LineEncoding.BaudRateBPS);
343 }