Engineers Garage

  • Projects and Tutorials
    • Electronic Projects
      • 8051
      • Arduino
      • ARM
      • AVR
      • PIC
      • Raspberry pi
      • STM32
    • Tutorials
    • Circuit Design
    • Project Videos
    • Components
  • Articles
    • Tech Articles
    • Insight
    • Invention Stories
    • How to
    • What Is
  • News
    • Electronic Products News
    • DIY Reviews
    • Guest Post
  • Forums
    • EDABoard.com
    • Electro-Tech-Online
    • EG Forum Archive
  • Digi-Key Store
    • Cables, Wires
    • Connectors, Interconnect
    • Discrete
    • Electromechanical
    • Embedded Computers
    • Enclosures, Hardware, Office
    • Integrated Circuits (ICs)
    • Isolators
    • LED/Optoelectronics
    • Passive
    • Power, Circuit Protection
    • Programmers
    • RF, Wireless
    • Semiconductors
    • Sensors, Transducers
    • Test Products
    • Tools
  • EE Resources
    • DesignFast
    • LEAP Awards
    • Oscilloscope Product Finder
    • White Papers
    • Webinars
  • EE Learning Center
    • Design Guides
      • WiFi & the IOT Design Guide
      • Microcontrollers Design Guide
      • State of the Art Inductors Design Guide
  • Women in Engineering

Atmega 32u4 Based UART to USB Converter (Part 12/25)

By Amanpreet Singh

UART was a popular serial interface in the past times. Still, a lot of embedded system devices uses UART for serial communication. However nowadays, the personal computers do not have RS-232 ports but have only the USB ports for serial communication. In this project, an UART to USB converter is designed to enable connecting embedded devices having UART interface to the personal computers. The project device works like a virtual serial device. That means that the data packets from the host computer are received according to the USB protocol and data packets from the connecting embedded device are received according to UART protocol but the project device will change the protocol in-between while the PC will be acknowledged that it is connected to a USB peripheral and the connecting embedded device will be acknowledged that it is connected to a computer having UART interface. The 8-bit USB AVR – Atmega 32u4 is used as the controller chip in the project. The project uses AVR based Lightweight USB Framework (LUFA) as the firmware which will be modified to perform the protocol conversion.

The LUFA’s communication device class (CDC) is modified to program the project. By using the LUFA firmware, the device driver code to implement USB protocol and the UART protocol will not needed to be written explicitly. By only using an API provided in the open source framework, the conversion between the protocols will be done.

Prototype of Arduino Based USB to UART and UART to USB Converter

Fig. 1: Prototype of Arduino Based USB to UART and UART to USB Converter 

The device does to need any human inputs. The USB data is received by the project device from the USB port of the Arduino Pro Micro. For UART, Tx and Rx pins of the Arduino Pro Micro are connected with the UART interface of the connecting embedded device.

PREREQUISITES

This project is based on Arduino Pro Micro which has the USB AVR – Atmega 32u4 as the sitting MCU. In order to understand this project, one must have basic knowledge of the AVR microcontrollers and the embedded C programming for AVRs. WinAVR Studio is used to write, edit and compile the project code, so closely following the project shall require familiarizing with the above stated IDE as well. Though LUFA framework takes care of implementing the USB protocol as well as UART protocol and has APIs to abstract the lower level codes, understanding USB protocol is recommended to understand how actually the project is working. In fact, if anyone has already worked on some other microcontroller, it will not be much pain to understand and follow the project. The project is based on using APIs of the LUFA framework and modifying the demo files that comes with the framework itself.

Image showing characters sent by Arduino to PC via Serial Device

Fig. 2: Image showing characters sent by Arduino to PC via Serial Device

COMPONENTS REQUIRED

1. Arduino Pro Micro

2. Connecting wires

3. Micro USB cable

SOFTWARE TOOLS REQUIRED

1. WinAVR Studio

2. AVR Dude

3. LUFA Firmware

BLOCK DIAGRAM

Block Diagram of Arduino based USB to UART and UART to USB Converter

Fig. 3: Block Diagram of Arduino based USB to UART and UART to USB Converter 

CIRCUIT CONNECTIONS

The project is built on Arduino Pro Micro in which Atmega 32u4 works as the controller chip. The USB to UART and UART to USB protocol conversion is carried out on the Arduino board itself. The Arduino board has in-built USB port to connect with the personal computer and has Tx and Rx pins for serial communication on UART. So only the Arduino board is needed and connecting wires for connecting with embedded device having UART interface and USB cable for connecting with the PC are required. The Program code for the project is burnt to the Arduino Pro Micro using AVR Dude. Once the firmware is loaded to the Arduino board, it can be used for UART to USB and USB to UART conversion.

HOW THE PROJECT WORKS

In this project both USB and UART protocol are used and an API of virtual serial device from the LUFA framework is employed to implement the project. The device is configured to communication device class (CDC). For USB to USART and USART to USB conversion, the device is configured to Abstract Control Model Subclass.

The USB communications device class (CDC) is a composite USB device class, and the class may include more than one interface. The CDC is used primarily for modems, but also for ISDN, fax machines, and telephony applications for performing regular voice calls. The Abstract Control Model subclass of CDC bridges the gap between legacy modem devices and USB devices, enabling the use of application programs designed for older modems.

Image of Arduino Based USB to UART and UART to USB Converter

Fig. 4: Image of Arduino Based USB to UART and UART to USB Converter 

The project is USB CDC class device.  In the LUFA framework CDC class related modules are in the LUFA-Source-Folder /LUFA/Drivers/USB/Class/Device folder. Other device class related module are also in the same folder. The LUFA framework has demo projects for different USB device classes in the LUFA-Source-FolderDemosDeviceClassDriver folder. For implementing the project, demo project for virtual serial  device provided in the LUFA framework will be modified and complied. The demo project for virtual serial device is in the LUFA-Source-FolderDemosDeviceClassDriverVirtualSerial folder. The folder contains VirtualSerial.c file which will be modified to implement the project.

How VirtualSerial.c identifies device a CDC USB Device

The VirtualSerial.c uses VirtualSerial_CDC_Interface interface in CDC_Device_USBTask () function which is being imported from the CDCDeviceClass.c (from LUFA-Source-Folder LUFADriversUSBClassDevice) to configure the device as USB CDC device. The interface abstracts the low-level descriptor codes and identifies the device as CDC device through an InterfaceNumber variable.

USB CDC Specific Descriptors

Like any HID device configure and exchange data with the host by sending descriptors in response to requests from the host device, the USB CDC devices also connect with a host via request-descriptor mechanism. At application layer descriptors are structured in the form of reports. Every report descriptor has a report structure. A report descriptor contains the information needed by host to determine the data format and how the data should be processed by the host. Therefore, a report descriptor basically structure the data that needs to be exchanged with the host according to the USB protocol.

When an USB CDC device is connected to the host computer, the host sends request for configuration in the form of control transfer. This is common for all USB peripherals or devices. Any CDC device for configuring with a host has to respond with Class Request, Class Notification and Endpoint Configuration. These information are passed through the Usage report to the host as the Usage Report informs the Host about the features or functionality of the USB device.

The usage and data report associated with CDC USB devices are defined in the CDCClassCommon.h file in the LUFA framework. The file is located in the LUFA-Source-Folder/LUFA/Drivers/USB/Class/Common folder. The CDC class allows an USB device to connect with various other interfaces and protocols like for the ISDN, fax, Ethernet, telephone etc. In the usage  report, a CDC device has to acknowledge its class, subclass and protocol values.

In CDCClassCommon.h, the subclass protocols of the CDC class are mentioned through an enum CDC_Descriptor_ClassSubclassProtocol_t in the following manner.

Screenshot of CDC_Descriptor_ClassSubclassProtocol_t Descriptor

Fig. 5: Screenshot of CDC_Descriptor_ClassSubclassProtocol_t Descriptor

The device designed in this project uses Abstract Control Model (ACM) protocol.  By LUFA, any CDC class device can respond to following control requests.

1. Send Encapsulated Command

2. Get Encapsulated Response

3. Set Line Encoding

4. Get Line Encoding

5. Set Control Line State

6. Send Break

These codes for these requests are mentioned in the LUFA in the following manner.

Screenshot of Codes for requests of Abstract Control Model (ACM) protocol

Fig. 6: Screenshot of Codes for requests of Abstract Control Model (ACM) protocol

Of these, the ACM subclass device responds to only three control requests.

Table listing control requests of ACM Subclass Device

Fig. 7: Table listing control requests of ACM Subclass Device

The descriptor in response to Set Line Coding request has the following field values.

Table listing fields of descriptor in response to Set Line Coding request

Fig. 8: Table listing fields of descriptor in response to Set Line Coding request

The descriptor in response to Get Line Coding request has the following field values.

Table listing fields of descriptor in response to Get Line Coding request

Fig. 9: Table listing fields of descriptor in response to Get Line Coding request

The descriptor in response to Set Control Line State request has the following field values.

Table listing fields of descriptor in response to Set Control Line State request

Fig. 10: Table listing fields of descriptor in response to Set Control Line State request 

For ACM Subclass CDC devices, the line coding structure is defined in the following manner.

Table listing  line coding structure of ACM Subclass CDC devices

Fig. 11: Table listing  line coding structure of ACM Subclass CDC devices

The Set Line Encoding request allows the host to specify typical asynchronous line-character formatting properties while get Line Encoding request allows the host to find out the currently configured line coding. The ACM line encoding format mentioned above is received or sent to the host from the device in the data packet of the descriptors responding to Set_Line_Coding and Get_Line_Coding requests respectively.

For line coding scheme, in LUFA, the CDC_LineEncodingFormats_t enum defined in CDCClassCommon.h has the character format values defined in the following manner.

Screenshot of CDC_LineEncodingFormats_t enum defined in CDCClassCommon.h

Fig. 12:Screenshot of CDC_LineEncodingFormats_t enum defined in CDCClassCommon.h

In CDCCLassCommon.h only, the CDC_LineEncodingParity_t enum has the values for parity type defined in the following manner.

Screenshot of values for parity type defined in CDC_LineEncodingParity_t enum in CDCClassCommon.h

Fig. 13: Screenshot of values for parity type defined in CDC_LineEncodingParity_t enum in CDCClassCommon.h

The control signal bitmap which is sent on Set Control Line State request has the following format in its descriptor.

Table listing control signal bitmap sent on Set Control Line State request

Fig. 14: Table listing control signal bitmap sent on Set Control Line State request 

These requests are made by the host when the device acknowledge itself to be a CDC class device. After configuring as ACM subclass, the device has to respond to a class notification to the host to describe the type of interface. For ACM subclass, following notification is received from the host.

Table listing notification received from the host for ACM Subclass

Fig. 15: Table listing notification received from the host for ACM Subclass

Again device responds with a descriptor having the following Field Values.

Table listing descriptor responded by the USB device

Fig. 16: Table listing descriptor responded by the USB device

The UART bitmap sent in the descriptor responding to the Serial_State notification has the following format.

Table listing Serial_State notification of UART bitmap sent in the descriptor

Fig. 17: Table listing Serial_State notification of UART bitmap sent in the descriptor  

In CDCCLassCommon.h, the descriptor sent by the device to configure device as CDC subclass device in the form of a data report is defined in the following manner.

Screenshot of data report in CDCCLassCommon.h

Fig. 18: Screenshot of data report in CDCCLassCommon.h

The descriptors specific to a subclass have the following data report definition.

Screenshot of data report definitions

Fig. 19: Screenshot of data report definitions

The data reports for configuring to ACM subclass has been defined in the following manner in CDCClassCommon.h.

Screenshot of data reports for configuring to ACM subclass in CDCClassCommon.h

Fig. 20: Screenshot of data reports for configuring to ACM subclass in CDCClassCommon.h

The descriptors specific to ACM subclass have the following data report definition in the CDCClassCommon.h.

Screenshot of descriptors specific to ACM subclass in CDCClassCommon.h

Fig. 21: Screenshot of descriptors specific to ACM subclass in CDCClassCommon.h

How a CDC Class device is enumerated can be understood from the following endpoint configuration table.

Endpoint Configuration Table for CDC Class device

Fig. 22: Endpoint Configuration Table for CDC Class device

Therefore, when the device is connected to the computer, first through control transfer at endpoint zero, host makes standard request and class requests to which the device responds with descriptors mentioned above. Then through an interrupt transfer at endpoint 0, the device sends another descriptor to the host and notifies it for serial interface and communication. The descriptor for state notification has also been already described above. After the state notification, the device and host get configured to carry out bulk transfers for data transmission between them.

The data reports that are sent to the host in bulk transfers for data transmission between the host and device have definition according to the following structure defined in CDCClassCommon.h.

Screenshot of Data Reports in CDCClassCommon.h

Fig. 23: Screenshot of Data Reports in CDCClassCommon.h

From Where VirtualSerial.C gets the USAGE and Data Report Descriptors

In the LUFA framework’s demo project for Virtual Serial, VirtualSerial.c file imports VirtualSerial.h where the descriptors.h is imported. The descriptor.h has the structures defining CDC class related descriptors which have been explained above. The VirtualSerial.c imports VirtualSerial.h which imports usb.h. USB.h imports CDCCLass.h. In CDCClass.h is imported CDCClassDevice.h. The CDCClassDevice.h imports CDCClassCommon.h where the CDC device specific descriptor fields have been defined.

HOW THE DEVICE WORKS

The device needs to be connected between the PC and the embedded system having UART interface. The Arduino board itself is the complete project device. In the project code additional library for UART is imported and the main() function of the VirtualSerial.c is modified to work the device like a protocol changer. Check out the program code to see the modifications implemented for building the project.

PROGRAMMING GUIDE

For building the project download the LUFA framework from the github.com.  The demo project provided with the LUFA framework is modified to make the device. In the extracted LUFA zip file, open Demos/Device/ClassDriver/VirtualSerial folder. The folder has the following files and folders.

Screenshot of LUFA Library Folder on Windows

Fig. 24: Screenshot of LUFA Library Folder on Windows

Of these, VirtualSerial.h, VirtualSerial.c and Makefile needs to be modified for the project. The modified files (provided at the bottom of the article in zip format) can also be downloaded from the engineersgarage and replaced with the original files. Either open the files in WinAVR Studio or Notepad++ and modify original files or replace files with the already modified one. The modified or replaced VirtualSerial.c needs to be compiled from within the LUFA’s Source folder to get the object code.

Modifying VirtualSerial.h

The VirtualSerial.h library file is imported in the VirtualSerial.c file and includes a set of additional libraries and defines the constants and functions for the joystick device. These include the additional libraries for the joystick, button and LEDs which should be commented out as the project is not using these features. So open VirtualSerial.h and make the following changes – :

• Comment the #include library statements for Joystick.h, LEDS.h, and (We are commenting these libraries as we are not using any joystick, buttons board and LED board)

• Comment the #define statements for LEDMASK_USB_NOTREADY, LEDMASK_USB_ENUMERATING, LEDMASK_USB_READY, LEDMASK_USB_ERROR

 

• Delete the function declaration for CheckJoystickMovement Save the file with changes

Modifying VirtualSerial.C file

Again in the VirtualSerial.c, the code sections for Joystick, button board and LEDs need to be commented out.  So open VirtualSerial.c and make the following changes – :

• In the main loop, comment the LEDs_SetAllLEDs()

• In SetupHardware() function, comment the Joystick_Init(), LEDs_Init()

• In EVENT_USB_Device_Connect() function, comment the LEDs_SetAllLEDs()

• In EVENT_USB_Device_Disconnect() function, comment LEDs_SetAllLEDs()

• In EVENT_USB_Device_ConfigurationChanged() function, comment the LEDs_SetAllLEDs()

• Also delete the CheckJoystickMovement function completely

In VirtualSerial.c the main() function executes the functioning of the protocol convertor device. First uart.h has to be included in the VirtualSerial.c So add the following statements in the beginning of file – :

#include “VirtualSerial.h”
#include “uart.h”

The following functions defined in the uart.h will be used in the program code.

Table listing functions defined in uart.h

Fig. 25: Table listing functions defined in uart.h

In the main() function, a variable OUT_Data to hold data sent by the host needs to be defined and a character buffer buff[] to hold data from UART has to be defined. The array representing character buffer has to set its last element as NULL character and UART has to be initialized using uart_init() function. A file variable has to be defined to contain data received from  the USB port. This has to be used as parameter in CDC_Device_CreateStream() function. The CDC_Device_CreateStream() function is defined in the CDCClassDevice.c file where other CDC Class Device related functions are also defined. The CDCClassDevice.c is located in the LUFA-Source-FolderLUFAUSBClassDevice folder. An infinite for loop is called in which data from USB port is assigned to OUT_Data variable using getc() function and is sent Tx pin of UART using uart_char() function. If any data from embedded device through UART is available, it is read through uart_read() function and is assigned to the buff[]. The data in buff[] is taken into ReportString pointer and sent to the computer using fputs() function. So replace the original body of the main function from the following code.

{
int OUT_Data; // serial data sent by host
char* ReportString  = NULL; // pointer to point to the received character from rx pin
char buff[2]; // buffer to hold the received character from rx pin
buff[1] = ‘’; // initialize the last character as NULL for string implementation
uart_init(103); // initialize UART with 9600bps
 
SetupHardware();
 
/* Create a regular character stream for the interface so that it can be used with the stdio.h functions */
CDC_Device_CreateStream(&VirtualSerial_CDC_Interface, &USBSerialStream);
 
//LEDs_SetAllLEDs(LEDMASK_USB_NOTREADY);
GlobalInterruptEnable();
 
for (;;)
{
OUT_Data = getc(&USBSerialStream); // store character received from Host. EOF indicates no character
 
/*
* Check if OUT_Data contains any character.
* Get the character from the file USBSerialStream until EOF
*/
 
while(OUT_Data!= EOF)
{
uart_char(OUT_Data); // send the character via hardware tx pin
OUT_Data = getc(&USBSerialStream);
}
 
/*
*  check if there is any data recieved on hardware Rx pin
*  if there is any data, add it to the buffer for transmission to host
*  else assign null to ReportString, which indicates no data received
*/
 
if(check_for_data_availability()) 
{
buff[0] = uart_read(); // read character from rx pin
ReportString = buff; // assign address
}
else
ReportString = NULL; // assign NULL
 
/*
* check if there is any data to send to Host
* if ReportString is NULL, it indicates no data received
*/
 
if ((ReportString != NULL))
{
 
/* Write the string to the virtual COM port via the created character stream */
fputs(ReportString, &USBSerialStream);
}
 
CDC_Device_USBTask(&VirtualSerial_CDC_Interface);
USB_USBTask();
}
}

Inside the infinite for loop the CDC_Device_USBTask() function is called where VirtualSerial_CDC_Interface interface is passed as parameter. The interface identifies the device as Virtual Serial device and abstracts the low level program code specific to CDC subclass. The function is coming from the CDCClassDevice.c module (located in LUFA/Drivers/USB/Class/Device/CDCClassDevice.c) and is used for general management task for a given CDC class interface, required for the correct operation of the interface. It should be called in the main program loop, before the master USB management task USB_USBTask(). The  USB_USBTask() is the main USB management task. The USB driver requires this task to be executed continuously when the USB system is active (device attached in host mode, or attached to a host in device mode) in order to manage USB communications. The function is defined in USBTask.c (Located in LUFA-Source-FolderLUFADriversUSBCore folder).

Save the file and create Make file for the project.

Modifying Make File

In the VirtualSerial folder there is a make file that needs to be edited. The file can be edited using Notepad++. The following information needs to be edited – :

• MCU = atmega32u4

• ARCH = AVR8

• BOARD = LEONARDO

• F_CPU = 16000000

Save the file and exit. Now all the files are edited completely for the USB-UART Protocol Convertor application.

Compiling VirtualSerial.cFor compiling the source code, WinAVR Programmers Notepad or Arduino IDE can be used. Open the modified VirtualSerial.c file and compile the code.

BURNING HEX CODE

The hex file is generated on compiling the VirtualSerial.c file. For burning the object code to microcontroller open the Command Prompt, change the current directory to the directory containing the Hex file. This can be done using command: CD <address of the directory>. Now reset the Arduino and instantly run the command: : avrdude -v -p atmega32u4 -c avr109 -P COM20 -b 57600 -D -Uflash:w:VirtualSerial.hex:i after replacing the COM Port with the recognized one.

INSTALLING DRIVERS

After successful burning, plug the device. If the device is not properly installed or detected, then device driver needs to be installed at Host end. The VirtualSerial folder contains LUFA VirtualSerial.inf file. Install the device driver with this inf file. The driver can be installed from the Device Manager. After the driver is successfully installed, the device will be shown as LUFA CDC Demo under Ports tab in the Device Manager.

Testing the device

For UART System (Peripheral) to Host communication testing, any Arduino Board can be used that can transmit characters to the Atmega32u4 via UART. The Tx pin of Arduino and the Rx pin of Atmega32u4 needs to be connected for testing.  The Atmega32u4 will transmit these received characters to the Host via USB. Any Serial monitor like RealTerm can be used at Host end to see the incoming data from the Virtual Serial Device.

The following program code can be loaded to any Arduino  board for  UART to Host test.

void setup() {
 Serial.begin(9600); // initialize serial communication with 9600 bps 
}
void loop() {
Serial.print(“hello”); // send hello string 
delay(500); // delay of 500 ms
}

For Host to UART System (Peripheral) communication testing, any Arduino Mega2560 board can be used that can receive characters from the Atmega32u4 via UART. The Mega board has three serial ports. The data on Serial port0 can be seen on PC.  A program can be build that can receive characters from the ATmega32u4 via UART port1 and will forward these characters to the UART port0. The Rx pin of Arduino and the Tx pin of Atmega32u4 needs to be connected for testing. The Arduino needs to be connected via USB to the PC to see the data at port0. For testing, transmit some characters from the RealTerm Serial monitor connected to Virtual Serial device. If the device is working properly, the received characters can be seen on Arduino Serial monitor connected to Arduino device.

The following program code can be loaded to Arduino Mega2560 for Host to UART test.

void setup() {

 Serial.begin(9600);  // initialize serial communication at port0 with 9600 bps
  Serial1.begin(9600); // initialize serial communication at port1 with 9600 bps
}
void loop() {
 if(Serial1.available() > 0)  // if there is any data received at port1
  Serial.print(Serial1.read()); // send the received data to port0
}

In the next project – Atmega 32u4 Based Virtual Serial Mouse, a composite device will be designed that will work as mouse as well as UART to USB converter.

Project Source Code

###

/*

             LUFA Library

     Copyright (C) Dean Camera, 2015.


  dean [at] fourwalledcubicle [dot] com

           www.lufa-lib.org

*/


/*

  Copyright 2015  Dean Camera (dean [at] fourwalledcubicle [dot] com)
  Permission to use, copy, modify, distribute, and sell this
  software and its documentation for any purpose is hereby granted
  without fee, provided that the above copyright notice appear in
  all copies and that both that the copyright notice and this
  permission notice and warranty disclaimer appear in supporting
  documentation, and that the name of the author not be used in
  advertising or publicity pertaining to distribution of the
  software without specific, written prior permission.


  The author disclaims all warranties with regard to this
  software, including all implied warranties of merchantability
  and fitness.  In no event shall the author be liable for any
  special, indirect or consequential damages or any damages
  whatsoever resulting from loss of use, data or profits, whether
  in an action of contract, negligence or other tortious action,
  arising out of or in connection with the use or performance of
  this software.

*/


/** file

 *

 *  Main source file for the VirtualSerial demo. This file contains the main tasks of

 *  the demo and is responsible for the initial application hardware configuration.

 */


#include "VirtualSerial.h"

#include "uart.h"


/** LUFA CDC Class driver interface configuration and state information. This structure is

 *  passed to all CDC Class driver functions, so that multiple instances of the same class

 *  within a device can be differentiated from one another.

 */

USB_ClassInfo_CDC_Device_t VirtualSerial_CDC_Interface =

{

.Config =

{

.ControlInterfaceNumber   = INTERFACE_ID_CDC_CCI,

.DataINEndpoint           =

{

.Address          = CDC_TX_EPADDR,

.Size             = CDC_TXRX_EPSIZE,

.Banks            = 1,

},

.DataOUTEndpoint =

{

.Address          = CDC_RX_EPADDR,

.Size             = CDC_TXRX_EPSIZE,

.Banks            = 1,

},

.NotificationEndpoint =

{

.Address          = CDC_NOTIFICATION_EPADDR,

.Size             = CDC_NOTIFICATION_EPSIZE,

.Banks            = 1,

},

},

};


/** Standard file stream for the CDC interface when set up, so that the virtual CDC COM port can be

 *  used like any regular character stream in the C APIs.

 */

static FILE USBSerialStream;



/** Main program entry point. This routine contains the overall program flow, including initial

 *  setup of all components and the main program loop.

 */

int main(void)

{

int OUT_Data; // serial data sent by host

char* ReportString  = NULL; // pointer to point to the received character from rx pin

char buff[2]; // buffer to hold the received character from rx pin

buff[1] = ''; // initialize the last character as NULL for string implementation

uart_init(103); // initialize UART with 9600bps


SetupHardware();


/* Create a regular character stream for the interface so that it can be used with the stdio.h functions */

CDC_Device_CreateStream(&VirtualSerial_CDC_Interface, &USBSerialStream);


//LEDs_SetAllLEDs(LEDMASK_USB_NOTREADY);

GlobalInterruptEnable();


for (;;)

{

OUT_Data = getc(&USBSerialStream); // store character received from Host. EOF indicates no character


/*

* Check if OUT_Data contains any character.

* Get the character from the file USBSerialStream until EOF

*/


while(OUT_Data!= EOF)

{

uart_char(OUT_Data); // send the character via hardware tx pin

OUT_Data = getc(&USBSerialStream);

}


/*

*  check if there is any data recieved on hardware Rx pin

*  if there is any data, add it to the buffer for transmission to host

*  else assign null to ReportString, which indicates no data received

*/


if(check_for_data_availability()) 

{

buff[0] = uart_read(); // read character from rx pin

ReportString = buff; // assign address

}

else

ReportString = NULL; // assign NULL


/*

* check if there is any data to send to Host

* if ReportString is NULL, it indicates no data received

*/


if ((ReportString != NULL))

{


/* Write the string to the virtual COM port via the created character stream */

fputs(ReportString, &USBSerialStream);

}


CDC_Device_USBTask(&VirtualSerial_CDC_Interface);

USB_USBTask();

}

}




/** Configures the board hardware and chip peripherals for the demo's functionality. */

void SetupHardware(void)

{

#if (ARCH == ARCH_AVR8)

/* Disable watchdog if enabled by bootloader/fuses */

MCUSR &= ~(1 << WDRF);

wdt_disable();


/* Disable clock division */

clock_prescale_set(clock_div_1);

#elif (ARCH == ARCH_XMEGA)

/* Start the PLL to multiply the 2MHz RC oscillator to 32MHz 
and switch the CPU core to run from it */

XMEGACLK_StartPLL(CLOCK_SRC_INT_RC2MHZ, 2000000, F_CPU);

XMEGACLK_SetCPUClockSource(CLOCK_SRC_PLL);


/* Start the 32MHz internal RC oscillator and start the DFLL 
to increase it to 48MHz using the USB SOF as a reference */

XMEGACLK_StartInternalOscillator(CLOCK_SRC_INT_RC32MHZ);

XMEGACLK_StartDFLL(CLOCK_SRC_INT_RC32MHZ, DFLL_REF_INT_USBSOF, F_USB);


PMIC.CTRL = PMIC_LOLVLEN_bm | PMIC_MEDLVLEN_bm | PMIC_HILVLEN_bm;

#endif


/* Hardware Initialization */

//Joystick_Init();

//LEDs_Init();

USB_Init();

}


/** Event handler for the library USB Connection event. */

void EVENT_USB_Device_Connect(void)

{

//LEDs_SetAllLEDs(LEDMASK_USB_ENUMERATING);

}


/** Event handler for the library USB Disconnection event. */

void EVENT_USB_Device_Disconnect(void)

{

//LEDs_SetAllLEDs(LEDMASK_USB_NOTREADY);

}


/** Event handler for the library USB Configuration Changed event. */

void EVENT_USB_Device_ConfigurationChanged(void)

{

bool ConfigSuccess = true;


ConfigSuccess &= CDC_Device_ConfigureEndpoints(&VirtualSerial_CDC_Interface);


//LEDs_SetAllLEDs(ConfigSuccess ? LEDMASK_USB_READY : LEDMASK_USB_ERROR);

}


/** Event handler for the library USB Control Request reception event. */

void EVENT_USB_Device_ControlRequest(void)

{

CDC_Device_ProcessControlRequest(&VirtualSerial_CDC_Interface);

}


/** CDC class driver callback function the processing of changes to the virtual

 *  control lines sent from the host..

 *

 *  param[in] CDCInterfaceInfo  Pointer to the CDC 
class interface configuration structure being referenced

 */

void EVENT_CDC_Device_ControLineStateChanged(USB_ClassInfo_CDC_Device_t *const CDCInterfaceInfo)

{

/* You can get changes to the virtual CDC lines in this callback; a common

  use-case is to use the Data Terminal Ready (DTR) flag to enable and

  disable CDC communications in your application when set to avoid the

  application blocking while waiting for a host to become ready and read

  in the pending data from the USB endpoints.

*/

bool HostReady = (CDCInterfaceInfo->State.ControlLineStates.HostToDevice & CDC_CONTROL_LINE_OUT_DTR) != 0;

}

###

 


Project Datasheet

https://www.engineersgarage.com/wp-content/uploads/2019/10/makefile_0.zip


Project Video


Filed Under: Electronic Projects

 

Questions related to this article?
👉Ask and discuss on Electro-Tech-Online.com and EDAboard.com forums.



Tell Us What You Think!! Cancel reply

You must be logged in to post a comment.

HAVE A QUESTION?

Have a technical question about an article or other engineering questions? Check out our engineering forums EDABoard.com and Electro-Tech-Online.com where you can get those questions asked and answered by your peers!


Featured Tutorials

  • PS2 Keyboard To Store Text In SD Card Using Arduino Circuit Setup On Breadboard
    How To Use PS2 Keyboard To Store Text In SD Card Using Arduino- (Part 42/49)
  • Wireless Path Tracking System Using Mouse, XBee And Arduino Circuit Setup On Breadboard
    How To Make A Wireless Path Tracking System Using Mouse, XBee And Arduino- (Part 43/49)
  • How to Make a Wireless Keyboard Using Xbee with Arduino- (Part 44/49)
  • Making Phone Call From GSM Module Using Arduino Circuit Setup On Breadboard
    How to Make Phonecall From GSM Module Using Arduino- (Part 45/49)
  • How to Make a Call using Keyboard, GSM Module and Arduino
    How To Make A Call Using Keyboard, GSM Module And Arduino- (Part 46/49)
  • Receiving SMS Using GSM Module With Arduino Prototype
    How to Receive SMS Using GSM Module with Arduino- (Part 47/49)

Stay Up To Date

Newsletter Signup

Sign up and receive our weekly newsletter for latest Tech articles, Electronics Projects, Tutorial series and other insightful tech content.

EE Training Center Classrooms

EE Classrooms

Recent Articles

  • How to interface a DS18B20 temperature sensor with MicroPython’s Onewire driver
  • What is a low power design?
  • Renesas partners with Tata to accelerate progress in advanced electronics
  • STMicroelectronics’ new touchscreen controller for smartphones enables longer runtime
  • Samsung unveils ISOCELL image sensor with industry’s smallest 0.56μm pixel

Most Popular

5G 555 timer circuit 8051 ai Arduino atmega16 automotive avr bluetooth dc motor display Electronic Part Electronic Parts Fujitsu ic infineontechnologies integratedcircuit Intel IoT ir lcd led maximintegratedproducts microchip microchiptechnology Microchip Technology microcontroller microcontrollers mosfet motor powermanagement Raspberry Pi remote renesaselectronics renesaselectronicscorporation Research samsung semiconductor sensor software STMicroelectronics switch Technology vishayintertechnology wireless

RSS EDABOARD.com Discussions

  • Interfacing LCD with PIC16F877 using CCS C Compiler
  • Effect of variable gain amplifier and LNA on the input RF signal's phase
  • How do you find the angle made by two isosceles triangles in a kite?
  • MWO - EM Structure missing
  • HF preamplifier with threshold?

RSS Electro-Tech-Online.com Discussions

  • Lighting a .010 green fiber optic with led
  • Help wanted to power an AC120v induction motor ( edited from Brushless motor - thank you @SHORTBUS= )
  • HELP NEEDED
  • NOR gate oscillator in LTspice not working
  • intro to PI
Engineers Garage
  • Analog IC TIps
  • Connector Tips
  • DesignFast
  • EDABoard Forums
  • EE World Online
  • Electro-Tech-Online Forums
  • Microcontroller Tips
  • Power Electronic Tips
  • Sensor Tips
  • Test and Measurement Tips
  • 5G Technology World
  • About Us
  • Contact Us
  • Advertise

Copyright © 2022 WTWH Media LLC. All Rights Reserved. The material on this site may not be reproduced, distributed, transmitted, cached or otherwise used, except with the prior written permission of WTWH Media
Privacy Policy | Advertising | About Us

Search Engineers Garage

  • Projects and Tutorials
    • Electronic Projects
      • 8051
      • Arduino
      • ARM
      • AVR
      • PIC
      • Raspberry pi
      • STM32
    • Tutorials
    • Circuit Design
    • Project Videos
    • Components
  • Articles
    • Tech Articles
    • Insight
    • Invention Stories
    • How to
    • What Is
  • News
    • Electronic Products News
    • DIY Reviews
    • Guest Post
  • Forums
    • EDABoard.com
    • Electro-Tech-Online
    • EG Forum Archive
  • Digi-Key Store
    • Cables, Wires
    • Connectors, Interconnect
    • Discrete
    • Electromechanical
    • Embedded Computers
    • Enclosures, Hardware, Office
    • Integrated Circuits (ICs)
    • Isolators
    • LED/Optoelectronics
    • Passive
    • Power, Circuit Protection
    • Programmers
    • RF, Wireless
    • Semiconductors
    • Sensors, Transducers
    • Test Products
    • Tools
  • EE Resources
    • DesignFast
    • LEAP Awards
    • Oscilloscope Product Finder
    • White Papers
    • Webinars
  • EE Learning Center
    • Design Guides
      • WiFi & the IOT Design Guide
      • Microcontrollers Design Guide
      • State of the Art Inductors Design Guide
  • Women in Engineering