3 Copyright (C) Dean Camera, 2009.
5 dean [at] fourwalledcubicle [dot] com
6 www.fourwalledcubicle.com
10 Copyright 2009 Dean Camera (dean [at] fourwalledcubicle [dot] com)
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.
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
31 #include "USBtoSerial.h"
34 /** Contains the current baud rate and other settings of the virtual serial port.
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.
39 CDC_Line_Coding_t LineCoding
= { .BaudRateBPS
= 9600,
40 .CharFormat
= OneStopBit
,
41 .ParityType
= Parity_None
,
44 /** Ring (circular) buffer to hold the RX data - data from the host to the attached device on the serial port. */
47 /** Ring (circular) buffer to hold the TX data - data from the attached device on the serial port to the host. */
50 /** Flag to indicate if the USART is currently transmitting data from the Rx_Buffer circular buffer. */
51 volatile bool Transmitting
= false;
53 /** Main program entry point. This routine configures the hardware required by the application, then
54 * starts the scheduler to run the application tasks.
60 /* Ring buffer Initialization */
61 Buffer_Initialize(&Rx_Buffer
);
62 Buffer_Initialize(&Tx_Buffer
);
64 LEDs_SetAllLEDs(LEDMASK_USB_NOTREADY
);
73 /** Configures the board hardware and chip peripherals for the demo's functionality. */
74 void SetupHardware(void)
76 /* Disable watchdog if enabled by bootloader/fuses */
77 MCUSR
&= ~(1 << WDRF
);
80 /* Disable clock division */
81 clock_prescale_set(clock_div_1
);
83 /* Hardware Initialization */
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.
92 void EVENT_USB_Connect(void)
94 /* Indicate USB enumerating */
95 LEDs_SetAllLEDs(LEDMASK_USB_ENUMERATING
);
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.
101 void EVENT_USB_Disconnect(void)
103 /* Reset Tx and Rx buffers, device disconnected */
104 Buffer_Initialize(&Rx_Buffer
);
105 Buffer_Initialize(&Tx_Buffer
);
107 /* Indicate USB not ready */
108 LEDs_SetAllLEDs(LEDMASK_USB_NOTREADY
);
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.
114 void EVENT_USB_ConfigurationChanged(void)
116 /* Setup CDC Notification, Rx and Tx Endpoints */
117 Endpoint_ConfigureEndpoint(CDC_NOTIFICATION_EPNUM
, EP_TYPE_INTERRUPT
,
118 ENDPOINT_DIR_IN
, CDC_NOTIFICATION_EPSIZE
,
119 ENDPOINT_BANK_SINGLE
);
121 Endpoint_ConfigureEndpoint(CDC_TX_EPNUM
, EP_TYPE_BULK
,
122 ENDPOINT_DIR_IN
, CDC_TXRX_EPSIZE
,
123 ENDPOINT_BANK_SINGLE
);
125 Endpoint_ConfigureEndpoint(CDC_RX_EPNUM
, EP_TYPE_BULK
,
126 ENDPOINT_DIR_OUT
, CDC_TXRX_EPSIZE
,
127 ENDPOINT_BANK_SINGLE
);
129 /* Indicate USB connected and ready */
130 LEDs_SetAllLEDs(LEDMASK_USB_READY
);
133 /** Event handler for the USB_UnhandledControlPacket event. This is used to catch standard and class specific
134 * control requests that are not handled internally by the USB library (including the CDC control commands,
135 * which are all issued via the control endpoint), so that they can be handled appropriately for the application.
137 void EVENT_USB_UnhandledControlPacket(void)
139 uint8_t* LineCodingData
= (uint8_t*)&LineCoding
;
141 /* Process CDC specific control requests */
142 switch (USB_ControlRequest
.bRequest
)
144 case REQ_GetLineEncoding
:
145 if (USB_ControlRequest
.bmRequestType
== (REQDIR_DEVICETOHOST
| REQTYPE_CLASS
| REQREC_INTERFACE
))
147 /* Acknowledge the SETUP packet, ready for data transfer */
148 Endpoint_ClearSETUP();
150 /* Write the line coding data to the control endpoint */
151 Endpoint_Write_Control_Stream_LE(LineCodingData
, sizeof(LineCoding
));
153 /* Finalize the stream transfer to send the last packet or clear the host abort */
158 case REQ_SetLineEncoding
:
159 if (USB_ControlRequest
.bmRequestType
== (REQDIR_HOSTTODEVICE
| REQTYPE_CLASS
| REQREC_INTERFACE
))
161 /* Acknowledge the SETUP packet, ready for data transfer */
162 Endpoint_ClearSETUP();
164 /* Read the line coding data in from the host into the global struct */
165 Endpoint_Read_Control_Stream_LE(LineCodingData
, sizeof(LineCoding
));
167 /* Finalize the stream transfer to clear the last packet from the host */
170 /* Reconfigure the USART with the new settings */
175 case REQ_SetControlLineState
:
176 if (USB_ControlRequest
.bmRequestType
== (REQDIR_HOSTTODEVICE
| REQTYPE_CLASS
| REQREC_INTERFACE
))
178 /* Acknowledge the SETUP packet, ready for data transfer */
179 Endpoint_ClearSETUP();
181 /* NOTE: Here you can read in the line state mask from the host, to get the current state of the output handshake
182 lines. The mask is read in from the wValue parameter in USB_ControlRequest, and can be masked against the
183 CONTROL_LINE_OUT_* masks to determine the RTS and DTR line states using the following code:
186 /* Acknowledge status stage */
187 while (!(Endpoint_IsINReady()));
195 /** Task to manage CDC data transmission and reception to and from the host, from and to the physical USART. */
201 /* NOTE: Here you can use the notification endpoint to send back line state changes to the host, for the special RS-232
202 handshake signal lines (and some error states), via the CONTROL_LINE_IN_* masks and the following code:
205 USB_Notification_Header_t Notification
= (USB_Notification_Header_t
)
207 .NotificationType
= (REQDIR_DEVICETOHOST
| REQTYPE_CLASS
| REQREC_INTERFACE
),
208 .Notification
= NOTIF_SerialState
,
211 .wLength
= sizeof(uint16_t),
214 uint16_t LineStateMask
;
216 // Set LineStateMask here to a mask of CONTROL_LINE_IN_* masks to set the input handshake line states to send to the host
218 Endpoint_SelectEndpoint(CDC_NOTIFICATION_EPNUM
);
219 Endpoint_Write_Stream_LE(&Notification
, sizeof(Notification
));
220 Endpoint_Write_Stream_LE(&LineStateMask
, sizeof(LineStateMask
));
224 /* Select the Serial Rx Endpoint */
225 Endpoint_SelectEndpoint(CDC_RX_EPNUM
);
227 /* Check to see if a packet has been received from the host */
228 if (Endpoint_IsOUTReceived())
230 /* Read the bytes in from the endpoint into the buffer while space is available */
231 while (Endpoint_BytesInEndpoint() && (BUFF_STATICSIZE
- Rx_Buffer
.Elements
))
233 /* Store each character from the endpoint */
234 Buffer_StoreElement(&Rx_Buffer
, Endpoint_Read_Byte());
237 /* Check to see if all bytes in the current packet have been read */
238 if (!(Endpoint_BytesInEndpoint()))
240 /* Clear the endpoint buffer */
245 /* Check if Rx buffer contains data - if so, send it */
246 if (Rx_Buffer
.Elements
)
247 Serial_TxByte(Buffer_GetElement(&Rx_Buffer
));
249 /* Select the Serial Tx Endpoint */
250 Endpoint_SelectEndpoint(CDC_TX_EPNUM
);
252 /* Check if the Tx buffer contains anything to be sent to the host */
253 if (Tx_Buffer
.Elements
)
255 /* Wait until Serial Tx Endpoint Ready for Read/Write */
256 while (!(Endpoint_IsReadWriteAllowed()));
258 /* Write the bytes from the buffer to the endpoint while space is available */
259 while (Tx_Buffer
.Elements
&& (Endpoint_BytesInEndpoint() < CDC_TXRX_EPSIZE
))
261 /* Write each byte retreived from the buffer to the endpoint */
262 Endpoint_Write_Byte(Buffer_GetElement(&Tx_Buffer
));
265 /* Remember if the packet to send completely fills the endpoint */
266 bool IsFull
= (Endpoint_BytesInEndpoint() == CDC_TXRX_EPSIZE
);
271 /* If no more data to send and the last packet filled the endpoint, send an empty packet to release
272 * the buffer on the receiver (otherwise all data will be cached until a non-full packet is received) */
273 if (IsFull
&& !(Tx_Buffer
.Elements
))
275 /* Wait until Serial Tx Endpoint Ready for Read/Write */
276 while (!(Endpoint_IsReadWriteAllowed()));
278 /* Send an empty packet to terminate the transfer */
285 /** ISR to handle the USART receive complete interrupt, fired each time the USART has received a character. This stores the received
286 * character into the Tx_Buffer circular buffer for later transmission to the host.
288 ISR(USART1_RX_vect
, ISR_BLOCK
)
290 /* Only store received characters if the USB interface is connected */
293 /* Character received, store it into the buffer */
294 Buffer_StoreElement(&Tx_Buffer
, UDR1
);
298 /** Reconfigures the USART to match the current serial port settings issued by the host as closely as possible. */
299 void ReconfigureUSART(void)
301 uint8_t ConfigMask
= 0;
303 /* Determine parity - non odd/even parity mode defaults to no parity */
304 if (LineCoding
.ParityType
== Parity_Odd
)
305 ConfigMask
= ((1 << UPM11
) | (1 << UPM10
));
306 else if (LineCoding
.ParityType
== Parity_Even
)
307 ConfigMask
= (1 << UPM11
);
309 /* Determine stop bits - 1.5 stop bits is set as 1 stop bit due to hardware limitations */
310 if (LineCoding
.CharFormat
== TwoStopBits
)
311 ConfigMask
|= (1 << USBS1
);
313 /* Determine data size - 5, 6, 7, or 8 bits are supported */
314 if (LineCoding
.DataBits
== 6)
315 ConfigMask
|= (1 << UCSZ10
);
316 else if (LineCoding
.DataBits
== 7)
317 ConfigMask
|= (1 << UCSZ11
);
318 else if (LineCoding
.DataBits
== 8)
319 ConfigMask
|= ((1 << UCSZ11
) | (1 << UCSZ10
));
321 /* Enable double speed, gives better error percentages at 8MHz */
322 UCSR1A
= (1 << U2X1
);
324 /* Enable transmit and receive modules and interrupts */
325 UCSR1B
= ((1 << RXCIE1
) | (1 << TXEN1
) | (1 << RXEN1
));
327 /* Set the USART mode to the mask generated by the Line Coding options */
330 /* Set the USART baud rate register to the desired baud rate value */
331 UBRR1
= SERIAL_2X_UBBRVAL((uint16_t)LineCoding
.BaudRateBPS
);