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" 
  33 /* Project Tags, for reading out using the ButtLoad project */ 
  34 BUTTLOADTAG(ProjName
,    "LUFA USB RS232 App"); 
  35 BUTTLOADTAG(BuildTime
,   __TIME__
); 
  36 BUTTLOADTAG(BuildDate
,   __DATE__
); 
  37 BUTTLOADTAG(LUFAVersion
, "LUFA V" LUFA_VERSION_STRING
); 
  39 /* Scheduler Task List */ 
  42         { Task
: USB_USBTask          
, TaskStatus
: TASK_STOP 
}, 
  43         { Task
: CDC_Task             
, TaskStatus
: TASK_STOP 
}, 
  47 /** Contains the current baud rate and other settings of the virtual serial port. 
  49  *  These values are set by the host via a class-specific request, and the physical USART should be reconfigured to match the 
  50  *  new settings each time they are changed by the host. 
  52 CDC_Line_Coding_t LineCoding 
= { BaudRateBPS
: 9600, 
  53                                  CharFormat
:  OneStopBit
, 
  54                                  ParityType
:  Parity_None
, 
  57 /** Ring (circular) buffer to hold the RX data - data from the host to the attached device on the serial port. */ 
  60 /** Ring (circular) buffer to hold the TX data - data from the attached device on the serial port to the host. */ 
  63 /** Flag to indicate if the USART is currently transmitting data from the Rx_Buffer circular buffer. */ 
  64 volatile bool Transmitting 
= false; 
  66 /** Main program entry point. This routine configures the hardware required by the application, then 
  67  *  starts the scheduler to run the application tasks. 
  71         /* Disable watchdog if enabled by bootloader/fuses */ 
  72         MCUSR 
&= ~(1 << WDRF
); 
  75         /* Disable Clock Division */ 
  76         SetSystemClockPrescaler(0); 
  78         /* Hardware Initialization */ 
  82         /* Ringbuffer Initialization */ 
  83         Buffer_Initialize(&Rx_Buffer
); 
  84         Buffer_Initialize(&Tx_Buffer
); 
  86         /* Indicate USB not ready */ 
  87         UpdateStatus(Status_USBNotReady
); 
  89         /* Initialize Scheduler so that it can be used */ 
  92         /* Initialize USB Subsystem */ 
  95         /* Scheduling - routine never returns, so put this last in the main function */ 
  99 /** Event handler for the USB_Connect event. This indicates that the device is enumerating via the status LEDs and 
 100  *  starts the library USB task to begin the enumeration and USB management process. 
 102 EVENT_HANDLER(USB_Connect
) 
 104         /* Start USB management task */ 
 105         Scheduler_SetTaskMode(USB_USBTask
, TASK_RUN
); 
 107         /* Indicate USB enumerating */ 
 108         UpdateStatus(Status_USBEnumerating
); 
 111 /** Event handler for the USB_Disconnect event. This indicates that the device is no longer connected to a host via 
 112  *  the status LEDs and stops the USB management and CDC management tasks. 
 114 EVENT_HANDLER(USB_Disconnect
) 
 116         /* Stop running CDC and USB management tasks */ 
 117         Scheduler_SetTaskMode(CDC_Task
, TASK_STOP
); 
 118         Scheduler_SetTaskMode(USB_USBTask
, TASK_STOP
); 
 120         /* Indicate USB not ready */ 
 121         UpdateStatus(Status_USBNotReady
); 
 124 /** Event handler for the USB_ConfigurationChanged event. This is fired when the host set the current configuration 
 125  *  of the USB device after enumeration - the device endpoints are configured and the CDC management task started. 
 127 EVENT_HANDLER(USB_ConfigurationChanged
) 
 129         /* Setup CDC Notification, Rx and Tx Endpoints */ 
 130         Endpoint_ConfigureEndpoint(CDC_NOTIFICATION_EPNUM
, EP_TYPE_INTERRUPT
, 
 131                                        ENDPOINT_DIR_IN
, CDC_NOTIFICATION_EPSIZE
, 
 132                                    ENDPOINT_BANK_SINGLE
); 
 134         Endpoint_ConfigureEndpoint(CDC_TX_EPNUM
, EP_TYPE_BULK
, 
 135                                        ENDPOINT_DIR_IN
, CDC_TXRX_EPSIZE
, 
 136                                    ENDPOINT_BANK_SINGLE
); 
 138         Endpoint_ConfigureEndpoint(CDC_RX_EPNUM
, EP_TYPE_BULK
, 
 139                                        ENDPOINT_DIR_OUT
, CDC_TXRX_EPSIZE
, 
 140                                    ENDPOINT_BANK_SINGLE
); 
 142         /* Indicate USB connected and ready */ 
 143         UpdateStatus(Status_USBReady
); 
 146         Scheduler_SetTaskMode(CDC_Task
, TASK_RUN
); 
 149 /** Event handler for the USB_UnhandledControlPacket event. This is used to catch standard and class specific 
 150  *  control requests that are not handled internally by the USB library (including the CDC control commands, 
 151  *  which are all issued via the control endpoint), so that they can be handled appropriately for the application. 
 153 EVENT_HANDLER(USB_UnhandledControlPacket
) 
 155         uint8_t* LineCodingData 
= (uint8_t*)&LineCoding
; 
 157         /* Process CDC specific control requests */ 
 160                 case REQ_GetLineEncoding
: 
 161                         if (bmRequestType 
== (REQDIR_DEVICETOHOST 
| REQTYPE_CLASS 
| REQREC_INTERFACE
)) 
 163                                 /* Acknowedge the SETUP packet, ready for data transfer */ 
 164                                 Endpoint_ClearSetupReceived(); 
 166                                 /* Write the line coding data to the control endpoint */ 
 167                                 Endpoint_Write_Control_Stream_LE(LineCodingData
, sizeof(LineCoding
)); 
 169                                 /* Finalize the stream transfer to send the last packet or clear the host abort */ 
 170                                 Endpoint_ClearSetupOUT(); 
 174                 case REQ_SetLineEncoding
: 
 175                         if (bmRequestType 
== (REQDIR_HOSTTODEVICE 
| REQTYPE_CLASS 
| REQREC_INTERFACE
)) 
 177                                 /* Acknowedge the SETUP packet, ready for data transfer */ 
 178                                 Endpoint_ClearSetupReceived(); 
 180                                 /* Read the line coding data in from the host into the global struct */ 
 181                                 Endpoint_Read_Control_Stream_LE(LineCodingData
, sizeof(LineCoding
)); 
 183                                 /* Finalize the stream transfer to clear the last packet from the host */ 
 184                                 Endpoint_ClearSetupIN(); 
 186                                 /* Reconfigure the USART with the new settings */ 
 191                 case REQ_SetControlLineState
: 
 192                         if (bmRequestType 
== (REQDIR_HOSTTODEVICE 
| REQTYPE_CLASS 
| REQREC_INTERFACE
)) 
 195                                 /* NOTE: Here you can read in the line state mask from the host, to get the current state of the output handshake 
 196                                          lines. The mask is read in from the wValue parameter, and can be masked against the CONTROL_LINE_OUT_* masks 
 197                                          to determine the RTS and DTR line states using the following code: 
 200                                 uint16_t wIndex 
= Endpoint_Read_Word_LE(); 
 202                                 // Do something with the given line states in wIndex 
 205                                 /* Acknowedge the SETUP packet, ready for data transfer */ 
 206                                 Endpoint_ClearSetupReceived(); 
 208                                 /* Send an empty packet to acknowedge the command */ 
 209                                 Endpoint_ClearSetupIN(); 
 216 /** Task to manage CDC data transmission and reception to and from the host, from and to the physical USART. */ 
 222                 /* NOTE: Here you can use the notification endpoint to send back line state changes to the host, for the special RS-232 
 223                                  handshake signal lines (and some error states), via the CONTROL_LINE_IN_* masks and the following code: 
 226                 USB_Notification_Header_t Notification 
= (USB_Notification_Header_t
) 
 228                                 NotificationType
: (REQDIR_DEVICETOHOST 
| REQTYPE_CLASS 
| REQREC_INTERFACE
), 
 229                                 Notification
:     NOTIF_SerialState
, 
 232                                 wLength
:          sizeof(uint16_t), 
 235                 uint16_t LineStateMask
; 
 237                 // Set LineStateMask here to a mask of CONTROL_LINE_IN_* masks to set the input handshake line states to send to the host 
 239                 Endpoint_SelectEndpoint(CDC_NOTIFICATION_EPNUM
); 
 240                 Endpoint_Write_Stream_LE(&Notification
, sizeof(Notification
)); 
 241                 Endpoint_Write_Stream_LE(&LineStateMask
, sizeof(LineStateMask
)); 
 242                 Endpoint_ClearCurrentBank(); 
 245                 /* Select the Serial Rx Endpoint */ 
 246                 Endpoint_SelectEndpoint(CDC_RX_EPNUM
); 
 248                 if (Endpoint_ReadWriteAllowed()) 
 250                         /* Read the received data endpoint into the transmission buffer */ 
 251                         while (Endpoint_BytesInEndpoint()) 
 253                                 /* Wait until the buffer has space for a new character */ 
 254                                 while (!((BUFF_STATICSIZE 
- Rx_Buffer
.Elements
))); 
 256                                 /* Store each character from the endpoint */ 
 257                                 Buffer_StoreElement(&Rx_Buffer
, Endpoint_Read_Byte()); 
 260                         /* Clear the endpoint buffer */ 
 261                         Endpoint_ClearCurrentBank(); 
 264                 /* Check if Rx buffer contains data */ 
 265                 if (Rx_Buffer
.Elements
) 
 267                         /* Initiate the transmission of the buffer contents if USART idle */ 
 271                                 Serial_TxByte(Buffer_GetElement(&Rx_Buffer
)); 
 275                 /* Select the Serial Tx Endpoint */ 
 276                 Endpoint_SelectEndpoint(CDC_TX_EPNUM
); 
 278                 /* Check if the Tx buffer contains anything to be sent to the host */ 
 279                 if (Tx_Buffer
.Elements
) 
 281                         /* Wait until Serial Tx Endpoint Ready for Read/Write */ 
 282                         while (!(Endpoint_ReadWriteAllowed())); 
 284                         /* Check before sending the data if the endpoint is completely full */ 
 285                         bool IsFull 
= (Endpoint_BytesInEndpoint() == CDC_TXRX_EPSIZE
); 
 287                         /* Write the transmission buffer contents to the received data endpoint */ 
 288                         while (Tx_Buffer
.Elements 
&& (Endpoint_BytesInEndpoint() < CDC_TXRX_EPSIZE
)) 
 289                           Endpoint_Write_Byte(Buffer_GetElement(&Tx_Buffer
)); 
 292                         Endpoint_ClearCurrentBank(); 
 294                         /* If a full endpoint was sent, we need to send an empty packet afterwards to terminate the transfer */ 
 297                                 /* Wait until Serial Tx Endpoint Ready for Read/Write */ 
 298                                 while (!(Endpoint_ReadWriteAllowed())); 
 300                                 /* Send an empty packet to terminate the transfer */ 
 301                                 Endpoint_ClearCurrentBank(); 
 307 /** ISR to handle the USART transmit complete interrupt, fired each time the USART has sent a character. This reloads the USART 
 308  *  data register with the next byte from the Rx_Buffer circular buffer if a character is available, or stops the transmission if 
 309  *  the buffer is currently empty. 
 311 ISR(USART1_TX_vect
, ISR_BLOCK
) 
 313         /* Send next character if available */ 
 314         if (Rx_Buffer
.Elements
) 
 315           UDR1 
= Buffer_GetElement(&Rx_Buffer
); 
 317           Transmitting 
= false; 
 320 /** ISR to handle the USART receive complete interrupt, fired each time the USART has received a character. This stores the received 
 321  *  character into the Tx_Buffer circular buffer for later transmission to the host. 
 323 ISR(USART1_RX_vect
, ISR_BLOCK
) 
 325         /* Character received, store it into the buffer */ 
 326         Buffer_StoreElement(&Tx_Buffer
, UDR1
); 
 329 /** Function to manage status updates to the user. This is done via LEDs on the given board, if available, but may be changed to 
 330  *  log to a serial port, or anything else that is suitable for status updates. 
 332  *  \param CurrentStatus  Current status of the system, from the USBtoSerial_StatusCodes_t enum 
 334 void UpdateStatus(uint8_t CurrentStatus
) 
 336         uint8_t LEDMask 
= LEDS_NO_LEDS
; 
 338         /* Set the LED mask to the appropriate LED mask based on the given status code */ 
 339         switch (CurrentStatus
) 
 341                 case Status_USBNotReady
: 
 342                         LEDMask 
= (LEDS_LED1
); 
 344                 case Status_USBEnumerating
: 
 345                         LEDMask 
= (LEDS_LED1 
| LEDS_LED2
); 
 347                 case Status_USBReady
: 
 348                         LEDMask 
= (LEDS_LED2 
| LEDS_LED4
); 
 352         /* Set the board LEDs to the new LED mask */ 
 353         LEDs_SetAllLEDs(LEDMask
); 
 356 /** Reconfigures the USART to match the current serial port settings issued by the host as closely as possible. */ 
 357 void ReconfigureUSART(void) 
 359         uint8_t ConfigMask 
= 0; 
 361         /* Determine parity - non odd/even parity mode defaults to no parity */ 
 362         if (LineCoding
.ParityType 
== Parity_Odd
) 
 363           ConfigMask 
= ((1 << UPM11
) | (1 << UPM10
)); 
 364         else if (LineCoding
.ParityType 
== Parity_Even
) 
 365           ConfigMask 
= (1 << UPM11
); 
 367         /* Determine stop bits - 1.5 stop bits is set as 1 stop bit due to hardware limitations */ 
 368         if (LineCoding
.CharFormat 
== TwoStopBits
) 
 369           ConfigMask 
|= (1 << USBS1
); 
 371         /* Determine data size - 5, 6, 7, or 8 bits are supported */ 
 372         if (LineCoding
.DataBits 
== 6) 
 373           ConfigMask 
|= (1 << UCSZ10
); 
 374         else if (LineCoding
.DataBits 
== 7) 
 375           ConfigMask 
|= (1 << UCSZ11
); 
 376         else if (LineCoding
.DataBits 
== 8) 
 377           ConfigMask 
|= ((1 << UCSZ11
) | (1 << UCSZ10
)); 
 379         /* Enable double speed, gives better error percentages at 8MHz */ 
 380         UCSR1A 
= (1 << U2X1
); 
 382         /* Enable transmit and receive modules and interrupts */ 
 383         UCSR1B 
= ((1 << TXCIE1
) | (1 << RXCIE1
) | (1 << TXEN1
) | (1 << RXEN1
)); 
 385         /* Set the USART mode to the mask generated by the Line Coding options */ 
 388         /* Set the USART baud rate register to the desired baud rate value */ 
 389         UBRR1  
= SERIAL_2X_UBBRVAL((uint16_t)LineCoding
.BaudRateBPS
);