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 /* Scheduler Task List */ 
  36         { .Task 
= USB_USBTask          
, .TaskStatus 
= TASK_STOP 
}, 
  37         { .Task 
= CDC_Task             
, .TaskStatus 
= TASK_STOP 
}, 
  41 /** Contains the current baud rate and other settings of the virtual serial port. 
  43  *  These values are set by the host via a class-specific request, and the physical USART should be reconfigured to match the 
  44  *  new settings each time they are changed by the host. 
  46 CDC_Line_Coding_t LineCoding 
= { .BaudRateBPS 
= 9600, 
  47                                  .CharFormat  
= OneStopBit
, 
  48                                  .ParityType  
= Parity_None
, 
  51 /** Ring (circular) buffer to hold the RX data - data from the host to the attached device on the serial port. */ 
  54 /** Ring (circular) buffer to hold the TX data - data from the attached device on the serial port to the host. */ 
  57 /** Flag to indicate if the USART is currently transmitting data from the Rx_Buffer circular buffer. */ 
  58 volatile bool Transmitting 
= false; 
  60 /** Main program entry point. This routine configures the hardware required by the application, then 
  61  *  starts the scheduler to run the application tasks. 
  65         /* Disable watchdog if enabled by bootloader/fuses */ 
  66         MCUSR 
&= ~(1 << WDRF
); 
  69         /* Disable clock division */ 
  70         clock_prescale_set(clock_div_1
); 
  72         /* Hardware Initialization */ 
  76         /* Ring buffer Initialization */ 
  77         Buffer_Initialize(&Rx_Buffer
); 
  78         Buffer_Initialize(&Tx_Buffer
); 
  80         /* Indicate USB not ready */ 
  81         UpdateStatus(Status_USBNotReady
); 
  83         /* Initialize Scheduler so that it can be used */ 
  86         /* Initialize USB Subsystem */ 
  89         /* Scheduling - routine never returns, so put this last in the main function */ 
  93 /** Event handler for the USB_Connect event. This indicates that the device is enumerating via the status LEDs and 
  94  *  starts the library USB task to begin the enumeration and USB management process. 
  96 void EVENT_USB_Connect(void) 
  98         /* Start USB management task */ 
  99         Scheduler_SetTaskMode(USB_USBTask
, TASK_RUN
); 
 101         /* Indicate USB enumerating */ 
 102         UpdateStatus(Status_USBEnumerating
); 
 105 /** Event handler for the USB_Disconnect event. This indicates that the device is no longer connected to a host via 
 106  *  the status LEDs and stops the USB management and CDC management tasks. 
 108 void EVENT_USB_Disconnect(void) 
 110         /* Stop running CDC and USB management tasks */ 
 111         Scheduler_SetTaskMode(CDC_Task
, TASK_STOP
); 
 112         Scheduler_SetTaskMode(USB_USBTask
, TASK_STOP
); 
 114         /* Reset Tx and Rx buffers, device disconnected */ 
 115         Buffer_Initialize(&Rx_Buffer
); 
 116         Buffer_Initialize(&Tx_Buffer
); 
 118         /* Indicate USB not ready */ 
 119         UpdateStatus(Status_USBNotReady
); 
 122 /** Event handler for the USB_ConfigurationChanged event. This is fired when the host set the current configuration 
 123  *  of the USB device after enumeration - the device endpoints are configured and the CDC management task started. 
 125 void EVENT_USB_ConfigurationChanged(void) 
 127         /* Setup CDC Notification, Rx and Tx Endpoints */ 
 128         Endpoint_ConfigureEndpoint(CDC_NOTIFICATION_EPNUM
, EP_TYPE_INTERRUPT
, 
 129                                        ENDPOINT_DIR_IN
, CDC_NOTIFICATION_EPSIZE
, 
 130                                    ENDPOINT_BANK_SINGLE
); 
 132         Endpoint_ConfigureEndpoint(CDC_TX_EPNUM
, EP_TYPE_BULK
, 
 133                                        ENDPOINT_DIR_IN
, CDC_TXRX_EPSIZE
, 
 134                                    ENDPOINT_BANK_SINGLE
); 
 136         Endpoint_ConfigureEndpoint(CDC_RX_EPNUM
, EP_TYPE_BULK
, 
 137                                        ENDPOINT_DIR_OUT
, CDC_TXRX_EPSIZE
, 
 138                                    ENDPOINT_BANK_SINGLE
); 
 140         /* Indicate USB connected and ready */ 
 141         UpdateStatus(Status_USBReady
); 
 144         Scheduler_SetTaskMode(CDC_Task
, TASK_RUN
); 
 147 /** Event handler for the USB_UnhandledControlPacket event. This is used to catch standard and class specific 
 148  *  control requests that are not handled internally by the USB library (including the CDC control commands, 
 149  *  which are all issued via the control endpoint), so that they can be handled appropriately for the application. 
 151 void EVENT_USB_UnhandledControlPacket(void) 
 153         uint8_t* LineCodingData 
= (uint8_t*)&LineCoding
; 
 155         /* Process CDC specific control requests */ 
 156         switch (USB_ControlRequest
.bRequest
) 
 158                 case REQ_GetLineEncoding
: 
 159                         if (USB_ControlRequest
.bmRequestType 
== (REQDIR_DEVICETOHOST 
| REQTYPE_CLASS 
| REQREC_INTERFACE
)) 
 161                                 /* Acknowledge the SETUP packet, ready for data transfer */ 
 162                                 Endpoint_ClearSETUP(); 
 164                                 /* Write the line coding data to the control endpoint */ 
 165                                 Endpoint_Write_Control_Stream_LE(LineCodingData
, sizeof(LineCoding
)); 
 167                                 /* Finalize the stream transfer to send the last packet or clear the host abort */ 
 172                 case REQ_SetLineEncoding
: 
 173                         if (USB_ControlRequest
.bmRequestType 
== (REQDIR_HOSTTODEVICE 
| REQTYPE_CLASS 
| REQREC_INTERFACE
)) 
 175                                 /* Acknowledge the SETUP packet, ready for data transfer */ 
 176                                 Endpoint_ClearSETUP(); 
 178                                 /* Read the line coding data in from the host into the global struct */ 
 179                                 Endpoint_Read_Control_Stream_LE(LineCodingData
, sizeof(LineCoding
)); 
 181                                 /* Finalize the stream transfer to clear the last packet from the host */ 
 184                                 /* Reconfigure the USART with the new settings */ 
 189                 case REQ_SetControlLineState
: 
 190                         if (USB_ControlRequest
.bmRequestType 
== (REQDIR_HOSTTODEVICE 
| REQTYPE_CLASS 
| REQREC_INTERFACE
)) 
 192                                 /* Acknowledge the SETUP packet, ready for data transfer */ 
 193                                 Endpoint_ClearSETUP(); 
 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 in USB_ControlRequest, and can be masked against the 
 197                                                  CONTROL_LINE_OUT_* masks to determine the RTS and DTR line states using the following code: 
 200                                 /* Acknowledge status stage */ 
 201                                 while (!(Endpoint_IsINReady())); 
 209 /** Task to manage CDC data transmission and reception to and from the host, from and to the physical USART. */ 
 215                 /* NOTE: Here you can use the notification endpoint to send back line state changes to the host, for the special RS-232 
 216                                  handshake signal lines (and some error states), via the CONTROL_LINE_IN_* masks and the following code: 
 219                 USB_Notification_Header_t Notification 
= (USB_Notification_Header_t
) 
 221                                 .NotificationType 
= (REQDIR_DEVICETOHOST 
| REQTYPE_CLASS 
| REQREC_INTERFACE
), 
 222                                 .Notification     
= NOTIF_SerialState
, 
 225                                 .wLength          
= sizeof(uint16_t), 
 228                 uint16_t LineStateMask
; 
 230                 // Set LineStateMask here to a mask of CONTROL_LINE_IN_* masks to set the input handshake line states to send to the host 
 232                 Endpoint_SelectEndpoint(CDC_NOTIFICATION_EPNUM
); 
 233                 Endpoint_Write_Stream_LE(&Notification
, sizeof(Notification
)); 
 234                 Endpoint_Write_Stream_LE(&LineStateMask
, sizeof(LineStateMask
)); 
 238                 /* Select the Serial Rx Endpoint */ 
 239                 Endpoint_SelectEndpoint(CDC_RX_EPNUM
); 
 241                 /* Check to see if a packet has been received from the host */ 
 242                 if (Endpoint_IsOUTReceived()) 
 244                         /* Read the bytes in from the endpoint into the buffer while space is available */ 
 245                         while (Endpoint_BytesInEndpoint() && (BUFF_STATICSIZE 
- Rx_Buffer
.Elements
)) 
 247                                 /* Store each character from the endpoint */ 
 248                                 Buffer_StoreElement(&Rx_Buffer
, Endpoint_Read_Byte()); 
 251                         /* Check to see if all bytes in the current packet have been read */ 
 252                         if (!(Endpoint_BytesInEndpoint())) 
 254                                 /* Clear the endpoint buffer */ 
 259                 /* Check if Rx buffer contains data */ 
 260                 if (Rx_Buffer
.Elements
) 
 262                         /* Initiate the transmission of the buffer contents if USART idle */ 
 266                                 Serial_TxByte(Buffer_GetElement(&Rx_Buffer
)); 
 270                 /* Select the Serial Tx Endpoint */ 
 271                 Endpoint_SelectEndpoint(CDC_TX_EPNUM
); 
 273                 /* Check if the Tx buffer contains anything to be sent to the host */ 
 274                 if (Tx_Buffer
.Elements
) 
 276                         /* Wait until Serial Tx Endpoint Ready for Read/Write */ 
 277                         while (!(Endpoint_IsReadWriteAllowed())); 
 279                         /* Write the bytes from the buffer to the endpoint while space is available */ 
 280                         while (Tx_Buffer
.Elements 
&& (Endpoint_BytesInEndpoint() < CDC_TXRX_EPSIZE
)) 
 282                                 /* Write each byte retreived from the buffer to the endpoint */ 
 283                                 Endpoint_Write_Byte(Buffer_GetElement(&Tx_Buffer
)); 
 286                         /* Remember if the packet to send completely fills the endpoint */ 
 287                         bool IsFull 
= (Endpoint_BytesInEndpoint() == CDC_TXRX_EPSIZE
); 
 292                         /* If no more data to send and the last packet filled the endpoint, send an empty packet to release 
 293                          * the buffer on the receiver (otherwise all data will be cached until a non-full packet is received) */ 
 294                         if (IsFull 
&& !(Tx_Buffer
.Elements
)) 
 296                                 /* Wait until Serial Tx Endpoint Ready for Read/Write */ 
 297                                 while (!(Endpoint_IsReadWriteAllowed())); 
 299                                 /* Send an empty packet to terminate the transfer */ 
 306 /** ISR to handle the USART transmit complete interrupt, fired each time the USART has sent a character. This reloads the USART 
 307  *  data register with the next byte from the Rx_Buffer circular buffer if a character is available, or stops the transmission if 
 308  *  the buffer is currently empty. 
 310 ISR(USART1_TX_vect
, ISR_BLOCK
) 
 312         /* Send next character if available */ 
 313         if (Rx_Buffer
.Elements
) 
 314           UDR1 
= Buffer_GetElement(&Rx_Buffer
); 
 316           Transmitting 
= false; 
 319 /** ISR to handle the USART receive complete interrupt, fired each time the USART has received a character. This stores the received 
 320  *  character into the Tx_Buffer circular buffer for later transmission to the host. 
 322 ISR(USART1_RX_vect
, ISR_BLOCK
) 
 324         /* Only store received characters if the USB interface is connected */ 
 327                 /* Character received, store it into the buffer */ 
 328                 Buffer_StoreElement(&Tx_Buffer
, UDR1
); 
 332 /** Function to manage status updates to the user. This is done via LEDs on the given board, if available, but may be changed to 
 333  *  log to a serial port, or anything else that is suitable for status updates. 
 335  *  \param CurrentStatus  Current status of the system, from the USBtoSerial_StatusCodes_t enum 
 337 void UpdateStatus(uint8_t CurrentStatus
) 
 339         uint8_t LEDMask 
= LEDS_NO_LEDS
; 
 341         /* Set the LED mask to the appropriate LED mask based on the given status code */ 
 342         switch (CurrentStatus
) 
 344                 case Status_USBNotReady
: 
 345                         LEDMask 
= (LEDS_LED1
); 
 347                 case Status_USBEnumerating
: 
 348                         LEDMask 
= (LEDS_LED1 
| LEDS_LED2
); 
 350                 case Status_USBReady
: 
 351                         LEDMask 
= (LEDS_LED2 
| LEDS_LED4
); 
 355         /* Set the board LEDs to the new LED mask */ 
 356         LEDs_SetAllLEDs(LEDMask
); 
 359 /** Reconfigures the USART to match the current serial port settings issued by the host as closely as possible. */ 
 360 void ReconfigureUSART(void) 
 362         uint8_t ConfigMask 
= 0; 
 364         /* Determine parity - non odd/even parity mode defaults to no parity */ 
 365         if (LineCoding
.ParityType 
== Parity_Odd
) 
 366           ConfigMask 
= ((1 << UPM11
) | (1 << UPM10
)); 
 367         else if (LineCoding
.ParityType 
== Parity_Even
) 
 368           ConfigMask 
= (1 << UPM11
); 
 370         /* Determine stop bits - 1.5 stop bits is set as 1 stop bit due to hardware limitations */ 
 371         if (LineCoding
.CharFormat 
== TwoStopBits
) 
 372           ConfigMask 
|= (1 << USBS1
); 
 374         /* Determine data size - 5, 6, 7, or 8 bits are supported */ 
 375         if (LineCoding
.DataBits 
== 6) 
 376           ConfigMask 
|= (1 << UCSZ10
); 
 377         else if (LineCoding
.DataBits 
== 7) 
 378           ConfigMask 
|= (1 << UCSZ11
); 
 379         else if (LineCoding
.DataBits 
== 8) 
 380           ConfigMask 
|= ((1 << UCSZ11
) | (1 << UCSZ10
)); 
 382         /* Enable double speed, gives better error percentages at 8MHz */ 
 383         UCSR1A 
= (1 << U2X1
); 
 385         /* Enable transmit and receive modules and interrupts */ 
 386         UCSR1B 
= ((1 << TXCIE1
) | (1 << RXCIE1
) | (1 << TXEN1
) | (1 << RXEN1
)); 
 388         /* Set the USART mode to the mask generated by the Line Coding options */ 
 391         /* Set the USART baud rate register to the desired baud rate value */ 
 392         UBRR1  
= SERIAL_2X_UBBRVAL((uint16_t)LineCoding
.BaudRateBPS
);