Using the USART of AVR Microcontrollers : Reading and Writing Data

Till now we have seen the basics of RS232 communication, the function of level converter and the internal USART of AVR micro. After understanding the USART of AVR we have also written a easy to use function to initialize the USART. That was the first step to use RS232. Now we will see how we can actually send/receive data via rs232. As this tutorial is intended for those who are never used USART we will keep the things simple so as to just concentrate on the "USART" part. Of course after you are comfortable with usart you can make it more usable my using interrupt driven mechanism rather than "polling" the usart.

So lets get started! In this section we will make two functions :-

  • USARTReadChar() : To read the data (char) from the USART buffer.
  • USARTWriteChar(): To write a given data (char) to the USART.

This two functions will demonstrate the use of USART in the most basic and simplest way. After that you can easily write functions that can write strings to USART.

Reading From The USART : USARTReadChar() Function.

This function will help you read data from the USART. For example if you use your PC to send data to your micro the data is automatically received by the USART of AVR and put in a buffer and bit in a register (UCSRA) is also set to indicate that data is available in buffer. Its now your duty to read this data from the register and process it, otherwise if new data comes in the previous one will be lost. So the funda is that wait until the RXC bit (bit no 7) in UCSRA is SET and then read the UDR register of the USART.

(See the full description of USART registers)

char USARTReadChar()
   //Wait untill a data is available

   while(!(UCSRA & (1<<RXC)))
      //Do nothing

   //Now USART has got data from host
   //and is available is buffer

   return UDR;

Writing to USART : USARTWriteChar()

This function will help you write a given character data to the USART. Actually we write to the buffer of USART and the rest is done by USART, that means it automatically sends the data over RS232 line. One thing we need to keep in mind is that before writing to USART buffer we must first check that the buffer is free or not. It its not we simply wait until it is free. If its not free it means that USART is still busy sending some other data and once it finishes it will take the new data from buffer and start sending it.

Please not that the data held in the buffer is not the current data which the USART is busy sending. USART reads data from the buffer to its shift register which it starts sending and thus the buffer is free for your data. Every time the USART gets it data from buffer and thus making it empty it notifies this to the CPU by telling "USART Data Register Ran Empty" (UDRE) . It does so by setting a bit (UDRE bit no 5) in UCSRA register.

So in our function we first wait until this bit is set (by the USART ), once this is set we are sure that buffer is empty and we can write new data to it.

(See the full description of USART registers)

void USARTWriteChar(char data)
   //Wait until the transmitter is ready

   while(!(UCSRA & (1<<UDRE)))
      //Do nothing

   //Now write the data to USART buffer


Note: Actually their are two separate buffers, one for transmitter and one for receiver. But they share common address. The trick is that all "writes" goes to the Transmitter’s buffer while any "read" you performs comes from the receiver’s buffer.

That means if we read UDR we are reading from receivers buffer and when we are writing to UDR we are writing to transmitters buffer.

UDR=some_data; //Goes to transmitter

some_data=UDR; //Data comes from receiver

(See the full description of USART registers)

Sample program to use AVR USART

The following program makes use of the two functions we developed. This program simply waits for data to become available and then echoes it back via transmitter but with little modification. For example if you send "A" to it, it will send you back "[A]" that is input data but surrounded by square bracket. This program is enough to test the USART yet easy to understand.


A simple program to demonstrate the use of USART of AVR micro


See: for more info

Author : Avinash Gupta
Date : 29 Dec 2008

   ATmega8 @ 16MHz

   Suitable level converter on RX/TX line
   Connected to PC via RS232
   PC Software :  Hyper terminal @ 19200 baud
               No Parity,1 Stop Bit,
               Flow Control = NONE


#include <avr/io.h>
#include <inttypes.h>

//This function is used to initialize the USART
//at a given UBRR value
void USARTInit(uint16_t ubrr_value)

   //Set Baud rate

   UBRRL = ubrr_value;
   UBRRH = (ubrr_value>>8);

   /*Set Frame Format

   >> Asynchronous mode
   >> No Parity
   >> 1 StopBit

   >> char size 8



   //Enable The receiver and transmitter



//This function is used to read the available data
//from USART. This function will wait untill data is
char USARTReadChar()
   //Wait untill a data is available

   while(!(UCSRA & (1<<RXC)))
      //Do nothing

   //Now USART has got data from host
   //and is available is buffer

   return UDR;

//This fuction writes the given "data" to
//the USART which then transmit it via TX line
void USARTWriteChar(char data)
   //Wait untill the transmitter is ready

   while(!(UCSRA & (1<<UDRE)))
      //Do nothing

   //Now write the data to USART buffer


void main()
   //This DEMO program will demonstrate the use of simple

   //function for using the USART for data communication

   //Varriable Declaration
   char data;

   /*First Initialize the USART with baud rate = 19200bps
   for Baud rate = 19200bps

   UBRR value = 51


   USARTInit(51);    //UBRR = 51

   //Loop forever

      //Read data

      /* Now send the same data but but surround it in
      square bracket. For example if user sent 'a' our
      system will echo back '[a]'.





Running the USART Demo

You can run the above program in a ATmega8, ATmega16, ATmega32 cpu running at 16MHz without any modification. If you are using different clock frequency you have to change the UBRR value that we are passing to USARTInit() function. See previous tutorial for calculating UBRR value. AVR running the USART demo program can be interface to PC using following three ways.

  • Connect to a Physical COM Port.

    If you are lucky and own a really old PC then you may find a Physical COM port on your PC’s back. It is a 9 pin D type male connector. In this case you have to make a RS232 to TTL converter and connect the MCU to COM port via it.

  • Connect to a Virtual COM Port.

  • Those who are not so lucky may buy a Virtual COM port. Again in this case too you need to built a RS232 to TTL converter and connect the MCU to COM port via it.

    USB to Serial Adapter

    Fig. USB to Serial Converter


  • Connect Via a Chip CP2102.

    CP2102 is single chip USB to UART Bridge by SiLabs. This chip can be used to connect your embedded applications to USB port and enable them to transfer data with PC. It is the easiest path to build PC interfaced projects, like a PC controlled robot. We have a very good CP2102 module that can be used right out of the box. We have done all PCBs and fine SMD soldering for you.

    cp2102 usb to usart converter

    CP2102 Based Module.


    6 pin burg wire

    Female sides provide easy connection to headers.


    xboard mini v2.0

    xBoard MINI v2.0 with ATmega8 MCU


    ATmega8 Connected to CP2102


  • Connect via Chip PL2303

    PL2303 is yet another low cost chip for USB to serial (TTL Level) conversion. We also have a complete board for it too !

    pl2303 module

    PL2303 based USB to USART Module

Finding the COM port number of Serial Port

A PC can have several COM ports, each may have some peripheral connected to it like a Modem. Serial Ports on PC are numbered like COM1, COM2 … COMn etc. You first need to figure out in which COM port you have connected the AVR. Only after you have a correct COM port number you can communicate with the AVR using tools such as Hyperterminal. The steps below shows how to get COM port number in case of Virtual COM Ports.

Right Click on "My Computer" icon in Windows Desktop.

my computer icon

My Computer Icon on Windows Desktop

Select "Properties"

right click on my computer

System Context Menu

The System Properties will open up. Go to the "Hardware" Tab.

System Properties.

In Hardware tab select "Device Manager" button. It will open up device manager.

Open Device Manager

In Device Manager Find the Node "Ports (COM & LPT)"

Expand the PORT node in Device Manager

Depending on whether you are using a "USB to Serial Converter" or "CP2102 USB/USART Bridge Module" you have to find the port with following name.

Note down the COM port number next to the port name. You need to open this Port in Hyperterminal.

com port number

COM Port Number


com port number

COM Port Number

Communication using a Terminal Program on PC.

Since this is the introductory article about serial communication, we won’t be going in much detail on PC end COM port programming. For this reason we will be using a ready made software for sending and receiving serial data. I will be showing how to use two different terminal program to exchange data with embedded application.

Windows Hyperterminal

This is a default terminal program shipped with Windows OS. You can start it from

Start Menu->All Programs->Accessories->Communication->Hyperterminal.

Hyperterminal is not available in Windows Vista or Windows 7 so you have to use other terminal programs like RealTerm.

On startup it will ask for a connection name. Here we will enter AVR

Create New Connection

After that select a COM port you want to use. If you are using USB to serial adaptor please confirm which COM port number it is using. Other COM ports are usually connected to some device say an Internal modem etc. While some others are Bluetooth COM ports. Don’t use them. If you have a physical com port then most probably it will be COM1. If you select wrong COM port during this step you won’t be able to communicate with the AVR MCU and won’t get expected results.

hyperterminal setup for pic18f4520

Select COM Port

Now setup the COM port parameters as follows.

  • Bits per second: 19200
  • Data bits: 8
  • Parity: None
  • Stop bits: 1
  • Flow Control: None

com port setup

Setting up the COM port

HyperTerminal is ready for communication now! If everything went right HyperTerminal and AVR will talk happily and AVR will send the following message as we have programmed it.

avr atmega8 hyperterminal

Screenshot of Hyperterminal Showing the message received from AVR

If the screen shows similar message then you have successfully created a link between PC and your AVR micro. It shows that PC can read the data sent by AVR. To test if the AVR can also read Hyperterminal, press some keys on PC keyboard. Hyperterminal will send them over COM port to the AVR mcu where AVR will process the data. In the simple test program this processing includes returning the same data but enclosed inside [ and ], so if you press ‘k‘ then AVR will return [k]. If you are able to see this on PC screen then you are sure that AVR is receiving the data correctly.

That’s it! It fully tests the Serial Communication Routine and your hardware setup.

Setting Up Realterm and using it to communicate with AVR

If you are running Windows Vista or Windows 7 then the Hyperterminal Program may not be available. So in place of it you can use Realterm. It can be downloaded from here.

Start Realterm from its Desktop Icon. You will get a screen similar to this. Increase the Value of Row to 40 to see whole message.

avr atmega8 realterm

Screenshot of Realterm Showing the message received from AVR

Setup Realterm as follows. Go to the Port Tab and set it as follows.

  • Baud: 19200
  • Port: Port where you have connected the AVR
  • Data bits: 8
  • Parity: None
  • Stop bits: 1
  • Hardware Flow Control: None


avr atmega8 realterm

Screenshot of Realterm Setup

After setting up Realterm connect the AVR board with COM port and switch it on. Rest process is same as given above for Hyperterminal.

See Also


Avinash Gupta is solely focused on free and high quality tutorial to make learning embedded system fun !

More Posts - Website

Follow Me:
FacebookLinkedInGoogle Plus

113 thoughts on “Using the USART of AVR Microcontrollers : Reading and Writing Data

  • By Avinash - Reply


    That will require the knowledge abt the underlying robot hardware like sensor position and number etc …

  • By percy villegas t - Reply

    Hello Avinash

    I can send data from my Pc “C#” to Usart ”Atmega32” with RS232 line, it work without problem.

    Now I will send the information without RS232 line, I want send the information with Bluetooth. I need a Transmitter and receiver can you recommend me some who is easy to use?

    Why you don’t program in CodeVisionAVR it is much easy? And the program is gratis but you must also use AVR Studio for simulation. But write code is much easy with CodeVisionAVR.

    Thanks for all your help!!!!

    Percy Villegas.

  • By newman - Reply

    hi use this code for intrnal oscilator atmega8 8Mhz baud rate 9600. what all must i change? UBRR=51 ? or what change in software AVR Studio

  • By Ritesh - Reply

    Hello Avinash,

    you have used UCSRB=(1<<RXEN)|(1<<TXEN); for no interrupt , what should we use if there is a interrupt

  • By Ritesh - Reply

    Hello Avinash,

    you have used UCSRB=(1<<RXEN)|(1<<TXEN); for no interrupt , what should we use if there is a interrupt, Can you plz help me

  • By Ritesh - Reply

    hello avinash,

    there is a program in your tutorial which counts from 0-999 .i want to interface RS232 in the program (USART) so that I can see the increment from 0 to 999 in hyperterminal . I tried to combined your USART program with that but unscessful….
    can you please help me out

    thanking you
    ritesh kumar

  • By Nils - Reply


    Does anyone has this kind of program for a AVR STK128 board with an ATmega128.


  • By teja - Reply

    hello avinash
    nice job avinash, this is the best avr beginers forum i found on internet.
    i have a problem with with an usart implementation.
    i tried implementing an usart code for a quizbuzzer system (used 8mhz internal clk so i used USARTInit(25); ).The hyperterminal displayed junk values(like “..[ “) instead of the chars “1″ “2″ or “3″,when i used ur functions.
    i even implemented the code given above, but the heyperterminal wasn’t accepting any input or displaying any output.
    what could be the fault in this case?
    is there a way i can rectify it?
    i used a pc with vista installed in it and i used a hyperterminal 6.3 version downloaded from the internet(since i couldn’t find hyperterminal on vista)

  • By percy - Reply

    Hello AVANISH
    Now you can see what I have do with atmega_32 in the factory Talaris “Teller Cash Dispenser” there we regulate a motor. All the code is do in CodeVisionAVR. You can se the code and one video (10 minutes) about the project here.

    Why you don’t program in CodeVisionAVR? It is easier you know.


    Percy Villegas

  • By rajat - Reply

    hi avinash
    I burned your code on to my atmega16(4 Mhz external) and 4800 baud using avr burnomat with the settings as fuse>>clock options>>external clock>> ceramic, 3 – 8Mhz. however the hyperterminal shows some garbage value whenever i type character….can you help

  • By fabelizer - Reply

    Hi Avinash!

    Nice Tutorials!

    I just tried to build the code in AVR Studio 4, and have a couple of errors due to URSEL. Below is the message screen:

    Build started 31.5.2009 at 22:47:50
    avr-gcc -mmcu=attiny2313 -Wall -gdwarf-2 -Os -std=gnu99 -funsigned-char -funsigned-bitfields -fpack-struct -fshort-enums -MD -MP -MT RS232.o -MF dep/RS232.o.d -c ../RS232.c
    ../RS232.c: In function ‘USARTInit’:
    ../RS232.c:49: error: ‘URSEL’ undeclared (first use in this function)
    ../RS232.c:49: error: (Each undeclared identifier is reported only once
    ../RS232.c:49: error: for each function it appears in.)
    ../RS232.c: At top level:
    ../RS232.c:95: warning: return type of ‘main’ is not ‘int’
    make: *** [RS232.o] Error 1
    Build failed with 3 errors and 1 warnings…

    Am I missing a library? I never used ‘C’ before, and barely no anything about assembler….but learning!

    Thanks for all your great work!!!!

  • By Avinash - Reply


    try compiling for ATmega8

  • By fabelizer - Reply

    Will try it. I did go to the tiny3213 data sheet and found there was no such designation. Didn’t have time to check the megas though. I do think that will solve it. Thanks!

  • By gulab - Reply

    why 8051 uses standard baud rate of 9600bps????? reply to my mail

  • By luca - Reply

    Hi! all…
    I copied the source code into avr studio and build it with WinAvr..but the program doesn’t work…can somebody send the .hex file to it is so urgent..
    P.S. I’m using an atmega8 4MHz external clock 9600 boud..

  • By luca - Reply

    Thanks for help!!!

  • By Jeff - Reply

    Any plans to post something using interrupt-driven USART routines?

    • By Avinash - Reply


      I have the routines ready but I have to create documentation so that I can post it here.

  • Pingback: RF Communication Between Microcontrollers - Part II | eXtreme Electronics

  • By Siddharth Dev - Reply

    Hello Avinash,

    Again a great tutorial!! But “download a pdf version” tab is missing now..

  • By Amaury - Reply

    Thank you for this tutorial it was really help full I used it in an atmega32p with small tweeks to enable dual USART communications at two different speeds. Interrupt driven usart routines will be also very helpful!. Xon/Xoff flow control is something that it been driving me nuts!, do you know where can i get a sample code? or where can i get a better idea of how to implement it?

  • By mitul tailor - Reply

    i have tried to communicate my bot with pc through uart. i m using avr atmega8.but i m unable to transmit or receive the data. m using 16Mhz crystal.pls rply

  • By pran - Reply


    Thank u very much for all the tuts.I tried the above said program but when ever I type a letter in hyperteminal I only get a bunch of 9 C’s
    I dont understand.max232 cirkt is working.I looped it back and saw that working.
    Please reply to me as soon as possible.Your solution is worth to me.

  • By jig - Reply

    hi, really excellent beginner’s tutorial.

    Thanks for the job boss.

  • By Ray - Reply

    How do i test serial communication using windows vista (no hyperterminal with vista).



  • By rakesh - Reply

    Hello Avinash
    today i compile the code given by you in usart_demo.c but when i press f it give fþ6-
    and with other like that
    c >> f&-
    g >> æf

    can you tell me what is wrong here

  • By rakesh - Reply

    now i change MCU freqency to 12MHz,still error is same but echo back in other symbol.
    what freqency should i used for propare work of this module

  • By Blimey - Reply

    If you have Vista and need a terminal google PuttY… a helpfull tool..



  • By Avinash - Reply





  • By Shouvik - Reply

    hey Avinash..
    congratulations!! Your AVR series of tutorials are among the best that can be found on the internet. Its hard to believe that these tutorials are free of charge. I am doing a project with Atmega32. It uses usart to communicate to a ericsson phone. But the problem is I want pc communication at the same time.As the mobile would take up the usart port how can i implement serial communication for pc?? might be a naive question to ask but I am really confused..

    • By Avinash - Reply

      use a second software usart. if u know how usar works (given in details in one of the tuts) then u can easily implement in software . use it for less data intensive line.

  • By Shouvik - Reply

    hey avinash !!
    Thanx for the quick reply!! you are awesome!! Ya I found out how to use a software UART.Thanks.Cheerz

  • By Qasim - Reply

    plz help me

    i am using avr atmegs 32 and i am communication with pic microcontroller when i send character values like “ATP” it recognize n respond
    and for instance i have to send it data like “0100″ it dosend respond
    i am using functions defined above in this tutorial

    bt when i send 0100 through hyperterminal the pic controller recognize why does not it recognize integer values from my controller plz helo

  • By fabelizer - Reply


    You are really not sending an integer value, you are actually sending an ascii value. You must use a function such as atoi (ascii to integer) to convert to an integer if that is what you want to use. Check an ascii code table to see what integers the characters are really sending, and be sure your code can respond to them, or convert them.


  • By archerne - Reply

    great explanation! I am currently trying to put this on an ATMega128 board, and it is complaining about alot of things. I fixed alot of them by finding that the board this code was made for has 1 usart, while the one i am using has 2. however i think i got that working, now it is just complaining about the URSEL. any ideas?

  • By zahid - Reply

    the above code is working fine on Atmega32 and 16 but not on attiny2313.I have changed the statement

    UCSRC = (1 << UCSZ1) | (1 << UCSZ0);
    pls help…………

  • By AvrLabCom - Reply

    Hello, here is my C-ode for working with USART on ATTiny2313:

    void USART_Init( unsigned int baudrate ) //??????? ????????????? USART

    UBRRH = (unsigned char) (baudrate>>8);
    UBRRL = (unsigned char) baudrate;
    UCSRA = (1<<U2X); //???????? ????????
    UCSRB = ( ( 1 << RXEN ) | ( 1 << TXEN ) ); //?????????? ?? ????? ? ? ????????? ????? USART
    UCSRC = (1<<USBS) | (3<<UCSZ0);


    unsigned char USART_Receive( void ) //??????? ?????? ??????

    while ( !(UCSRA & (1<<RXC)) ); //???????? ?????? ???????

    return UDR; //??????? ???????

    void USART_Transmit( unsigned char data ) //??????? ???????? ??????
    while ( !(UCSRA & (1<<UDRE)) ); //???????? ??????????? ?????? ??????

    UDR = data; //?????? ???????? ??????

  • By aasma - Reply

    thanks for this amazing tutorial..
    i used the same code to program the ic i am using ATmega8535 running at 8Mhz and with a baud rate of UBRR=51.But when i type A on hyperterminal it returns A and not [A].can u plzz tell me what could be the possible problem.

  • By tina - Reply

    gr8 tutorials…
    I ve been working on a project on atmega32…
    I wanted to know if code vision avr is compatible with the atmega 32 development board…because the hyperterminal is not responding to the code…pls help…

  • By teo - Reply

    why we can’t aplly this USART for a hardware?
    (we use two ATnega 8535 with communication serial)

  • By Hari - Reply

    Hii Avinash,
    I used your code to read compass value using I2C on AtMega32 and display this value on my computer’s hyperterminal using rs232. the only problem I have is that the value is displayed as a character (ASCII), but I want to get this value as an integer or binary number, can you suggest me a way to do this.

  • By Salvador - Reply

    Answar !!

    You can do that with hyperterminal, they have that there.
    Or you can do that in your program.

    look here, i have work with atmega 32.

  • By Noldor - Reply

    Many thanks for these tutorials they are awesome!!

    but i have clarify this code from your sample program:

    In your sample program u wrote this

    UBRRL = ubrr_value;
    UBRRH = (ubrr_value>>8);

    instead of this just this (from prev tutorial)

    UBRR = ubrr_value;

    UBRR is 16bit so UBRRH+UBRRL right?
    so your sample program does this in UBRR (XXX is ubrr_value)
    0b00000XXX00000XXX right?
    so what is writen in UBRR if we write just this
    UBRR = ubrr_value
    is it the same, something else or did i get it completely wrong?

    thx for the answer and keep up this good work

    • By Avinash - Reply

      Both does the same thing.

  • Pingback: Interfacing RFID Reader with AVR MCUs - AVR Tutorial | eXtreme Electronics

  • By Gareth - Reply

    Hey Avinash! Your tutorials ROCK! Finished the LCD & ADC ones last night. This morning I planned on doing the RS232 one, but I discovered you needed a max232 ic. All the electronics stores were closed. So I made a plan to make another level converter. I stripped a few vcrs and power supplies looking for a few resistors, transistors and a diode. Im glad to report that it works PERFECTLY!!! :) )) Thanks again for all your help! G

  • By Jay - Reply

    Hi Avinash,
    I am using ur program to echo the chars. in realterm,but I am getting an error Break status in realterm,I have checked the circuit.Any help will be appreciated.


  • By uz - Reply

    hey Avi,
    Ur tutorial helps man,thanks.
    Please post on rs485 communication.Like how to transmitt and recieve data..

  • By hilmansyah - Reply

    dear avinash,

    Thanks to your project “Using the USART of AVR Microcontrollers : Reading and Writing Data”, it very usefull for me. I have some question regarding that project, I was build the circuit then burn the firmware to the chip, but I found the problem, baud rate only work in 1200 baud not in 19200 as your program. I already replace x’tal with the new one 16 MHz, but still can’t work in 19200.
    Second question, now I am doing to make project ADC USART AVR to Comm PC, and test with hyperterminal but symbol character show up, how to convert ansi character to integer??? can you give solution for my problem?


    best regard

  • By mKs - Reply

    hi bro, i m a gr8 fan of ur tuts. I followed all ur tuts till now successfully,
    I have a qn,
    Can we use this method to control the robot via PC?

  • By mKs - Reply

    can we use it to control the robo via PC?

  • By Tobbe - Reply

    Thank you for the code. Simple and easy to understand, I just started to learn C-code and via your code I did some step forward.
    Have you some code example about sending a command to toggle a pin on a port?

  • By kaba - Reply

    AVR and USART
    Project with ATMEGA8 and PC software.
    In the project is convert character to integer or single…

  • By SJ - Reply

    Hi, thanks for your write up.

    In your explanation you mention that the virtual com port also require RS232 to TTL converter. If the virtual com port is USB based converter isn’t necessary as the maximum voltage of USB protocol is +5V.

    • By Avinash - Reply


      The USB to Serial Adaptors (Virtual Com Ports) has a TTL to RS232 convertor in them. Which makes their i/o RS232 from the TTL voltage of USB. So again you need one for RS232 to TTL Convertor as you require on a real com port.

  • By jose albuja - Reply

    hola les hago una pregunta quiero enviar comandos AT a un atmega32 por comunicación serial..!!! como los puedo enviar tengo algo asi pero no me esta funcionando:

  • By vishwanath - Reply

    your tutorials have once again proved invaluable to me.however i have a small problem.if i need to control a motor using arrow keys from serial port,i ant do so,because,arrow keys dont have ascii values.please,i request you to help me out.

  • By Sandeep - Reply

    Dear Avinash,
    Thanks for nice tutorial. I want to know the maximum length of cable that can be supported for data transfer if we use CP2102 module.

  • By Avinash - Reply


    Which Side the USB Side or the UART Side?

    I don’t like technical people ask question which requires me to as a question in return!

    You had a risk of me deleting the comment straight away.

  • By kholis - Reply

    Dear Avinash,

    this is awesome.. I’ve tried using serial Attiny2313 with ACM(Abstract Communication Mode).
    It works in Windows and Ubuntu. But it doesn’t work in Linux Angstrom. I use Beagleboard with Linux Angstrom in it. So that, I can’t use that communication in Beagleboard.
    Is this serial CP2102 module using ACM?

    Thanks for your kindness

  • By Jithu Sunny - Reply

    Hi Avinash,
    Thanks once again for this simply wonderful tutorial series(I’m afraid you’ll get bored by seeing appreciation being crowded in your site..!)

    I request you to please see the following & give me some pointers on how to proceed,

    I have successfully loop-back tested your code using a CP2102 & an Atmega8.

    Then I added a 433 Mhz TX & RX pair in between this loop back(Of course another MCU to take output from). Now the problem is that in addition to the intended data, I’m getting continuous junk values interspersed with it.

    What is to be done to solve this?
    Interrupts? Else how?

  • By Jithu Sunny - Reply

    Fixed it. Sent data by prefixing a symbol(.). Sorry that I dint read your RF comm tut completely. Another query is regarding multithreading on Atmega8. How can it be done? Any pointers?


  • By Nikunj - Reply

    Can You tell me how to use the output given by USART into another program like in a c++ or c# program?

  • Pingback: interfacing PC(MATLAB) with AT89C51

  • Pingback: Visualize ADC data on PC Screen using USART - AVR Project | eXtreme Electronics

  • Pingback: Using the USART of AVR Microcontrollers. | eXtreme Electronics

  • By jk bawa - Reply

    hi, avinash.
    we are planing to make pressure horn melody, in the market many people make it, can you let us know how can we load songs in processor, that trigers the 6 relays and relays switch on the air pressure controllers.
    pls mail me the details

  • By Shahgufta - Reply

    Great work sir. Iam doing a project to send 32 bit data from atmega32 to pc using RS232 serial communication. I know to transfer 8 bit data but I dont know how to transfer 32 bit data. Please help me.


  • By Avinash - Reply


    To send 32 bit int using USART, use following snippet.

    uint32_t value=11998652; //32 bit unsigned int value


    on receiving side. Write

    uint32_t USARTReadUINT32();
    uint8_t b1,b2,b3,b4;


    return ((b4< <24)|(b3<<16)|(b2<<8)|(b1));

    for furthur discussion please use the forum.

  • Hello Sir,
    I am totally thankful for ur tutorials ,but i have a question,I have got ur CP2102 Based Module,which has successfully worked on Windows ,I have project to be implemented in Linux so would u please hint me about its use in Linux.Atlest some refrences,thanks .

  • By manfred - Reply

    Thank you soooo much.Very Helpful.Very Good. Greetings Manfred

  • By Suheb Naik - Reply

    Hello sir,
    i am very grateful for valuable information you have shared with us. However Our project is about encryption n decryption. and we are trying for PC-PC communication. First we will encrypt the msg & through the RF link pass it to another PC. There we will decrypt & then display. its wireless communication. Coding we are trying 2 do through Twofish algorithm. & the software for coding we are suppose 2 use is MATLAB. can you please guide us about coding part?

  • By TANISHA - Reply

    Hi Avinash,
    Ur tutorial is wonderful!!hats off to you!!
    I am currently doing a line follower project where i have to capture the data of the encoders,white line sensors and send them to pc!
    USARTReadChar() reads the data from USART buffer.But if i want to collect the data of encoders/WL sensors do i need to call the function USARTReadChar() using a port number??
    Please suggest!! cant understand really!!

    • By Avinash - Reply


      First of all thanks for your compliments! :)

      Sorry to tell but you’re confused!

      Please specify the type of encoders you are having may be the part number.

      White line sensors are usually simple IR pairs that uses reflectance to sense. Since these are raw IR led + Receiver pair. Their output need to be calibrated for the current application (due to change in parameters like the reflectance of the white surface in use, distance from the sensor, ambient IR intensity etc). These are usually connected to the ADC (Analog to Digital convertor port) of MCU. Reading the ADC channels will just give you the amount of IR radiation falling on them. You can then either make a auto calibrate function that scans the surface and finds the values sent by sensor for black and them white areas.

  • By TANISHA - Reply

    I am truly confused.
    “Please specify the type of encoders you are having may be the part number”
    Optical encoder MOC7811 is used for position encoder on the robot. It consists of IR LED and
    the photo transistor mounted in front of each other separated by a slot.
    Regarding the WL sensors I think that using the following code can give me the value of the sensor data.Awaiting ur expert opinion!mailing you the code!

    • By Avinash - Reply

      Your encoder just sends a pulse for each slot that passes under it. They are connected to

      external interrupt lines (INT4 & INT5). So your first task is to initiallize the INT4 and INT5.

      Now in the Interrupt service routine (ISR) you need to increment a varriable. After that you

      need some basic mathematics. You need to find out total number of slots in the encoder wheel.

      And using the radius of the main driving wheel you need to find out how much (in centimeters)

      your robot moves for each slot. So you can calculate the displacemnet easily.

      Tell me the following if you want me to write some working code for you.
      >> Number of slots in your encoder wheel.
      >> Circuit diagram of wiring of MOC7811 (does it gives high or low logic for slot)
      >> Are you using a ready made board for ATmega2560?
      >> If yes the make and model.
      >> Does it have a LCD module (will make our life easier)
      >> If yes the connection.
      >> The frequency at which your ATmega2560 is running (see the marking on crytal)
      >> How you are programming the ATmega2560 (which hardware/software you are using)
      >> Is your robot ready made or you have made all these (I mean encoder etc)
      >> Give me the photo of the encoder arrangement.
      >> If ready made name the make and model.

      • By TANISHA -

        Hi avinash!!
        Provided all the information u asked on ur mail id!!
        Eagerly waiting for ur reply!!

    • By Avinash - Reply


      Just configured my LCD library according to your platform.

      Please check if it works on your board.

      I have already tested on simulation software.

      Just confirm me. So that I can move on to write the code for position encoder test.

      Attached is the AVR Studio 5 Project.

      The hex file is in the location


      Burn the hex file and see if LCD works.

    • By Avinash - Reply


      Download the Basic Encoder Data Reading Demo from here

      This demo shows you how to get the raw encoder data to a variable.

      the two variables are


      for left and right encoders.

      This demo simply shows the contents of these variables on the LCD

      L: 00028 R: 00092

      L stands for Left and R for right.

      It is an AVR Studio 5 Project.

      The hex file is in the location

      Burn the hex file and see if works.

      After burning the program. Rotates the wheels by your hands.
      The LCD should update the counters.

      Tell me the results. So that we can proceed.

      • By TANISHA -

        hi avinash!!
        the 2nd zip file worked out.It is giving the readings as I manually rotate d wheels!!but how will I get the readings in the PC?

    • By Avinash - Reply


      That was just the basic demo to show you how you can read the encoder data into a variable.

      “but how will I get the readings in the PC?”

      So you want the encoder data on PC, so please let me know the following.

      >>Interface between PC and your Robot (Most probably UART).
      >>If USART the USART number (ATmega2560 has 4 USART viz USART0,USART1,USART2,USART3)
      >>Since PCs now a days don’t have a RS232 (COM Port), so their must be a convertor between your PC and the Robot, what is the type of it ? Is it built into the board?
      >> Have you installed the drivers for the above?
      >> What reading do you want on PC (the raw encoder data as shown on LCD, The distance in CM or velocity in CM/sec)
      >> You somewhere told that you wanted to plot some graph, so please describe the graph what will be in x and y axises.

      • By Rakesh -

        Thanks a lot sir ,whatever u are discussing it really boost us and makes feel good for learning and lost interest come back after reading the article sir please contiue like this “Very Very useful for New Beginners like us ”

        Thanks a lot Sir……..

  • By Robert - Reply

    Amazing tuts, awsome job
    was wondering if is there a way to send/recv integer directly without shifting, I mean, directly reading integer (numbers send from terminal and treat them such), also sending numbers(integers as numbers)
    well, I mean whats the most optimized thing to do, I know there are functions like (s)printf, but dont like it. just looking for the best way to send/recv int8 or int16

  • Pingback: how to display ADC to LCD and send to computer via USART

  • By sai - Reply

    stud level explanation
    can u tell me how to use the value transmitted to the pc as a input for some other program say a c program

  • Pingback: uart driver for pic16f877a - Page 3

  • By Manya - Reply

    Hi Avinash
    your tutorial is wonderful,it is very much understanble and simple
    i have a question,i am doing a temperature sensor project using PIC 16F1937,in that i wanted to read and send temperature readings to PC using RS232.can i use this program to for that.could you please help me.iam very new to this field.i dont know is this a silly question,please help me.

  • Pingback: GSM Module SIM300 Interface with AVR Amega32 | eXtreme Electronics

  • By Shilpa - Reply

    Dear Avinash,
    Thank you so much for your tutorial but I have a doubt abt a line in your program.

    UCSRC =(1<<URSEL)|(3<<UCSZ0);
    UCSRB =(1<<RXEN)|(1<<TXEN);

    is this correct or the code should be

    UCSRC |= (1<<URSEL)|(3<<UCSZ0);
    UCSRB |= (1<<RXEN)|(1<<TXEN);
    Sorry if this doubt is stupid. I am a beginner and bitwise operations confuse me a lot. Thank you

    • By Avinash - Reply


      The difference between my code and your suggestion is that, your code sets the bits like URSEL etc, and leaves other bits in the register. While mine set those bits and in addition it clear the other bits to 0.

      If MCU is executing your code after reset then the other bits will be 0 only, so in that case your and my code has same effect.

      But if some code has already touched those register before your code then you will have a register with value that you didn’t expect.

      Hope you have got it

      Other wise see this article to get a clear understanding of bit operations.

  • By ayan - Reply

    I have implemented this project.But l got nothing on REALTERM,HYPERTERMINAL &TERATERM.
    I have used atmega32a with 16MHz xtal.
    when i connected usb to serial converter( bafo bf-810 ) no com port is showing on device manager.
    But i have installed the driver to my Windows 7(32 bit).
    please help me.
    Thanks a lot for a nice tutorial.
    please reply to my EMAIL.

  • By ahad - Reply

    sir where are the libraries in the website i am unable to find please do help..

  • Pingback: AVR UBRR Calculator for Android | eXtreme Electronics

  • By Suraj - Reply

    hi avinash,
    It was so informative where you shows hardware installation of usb but I want to know that how to access any file using uart means accessing file from PC using uart. please notify me on my mail id (

  • By Irshad - Reply

    Sir,Please help me.Its urgent.I am using Realterm software.on receiving data,some symbol is displaying and it shows “Break Condition Received”.What Should I do

  • By Shash - Reply

    i am using win 7. how to get?

  • By JAY DABHI - Reply

    sir, i have used atmega16 for serial transmission.i have used bray’s terminal.i can send the data to mcu from pc.but i can’t recieve the data from microcontroller.what is the problem?

  • By aArOn - Reply

    thanks a lot sir.can you please post a tutorial on interrupt controlled USART ?

  • By Harry - Reply

    Sir,kindly provide the library for the other usart functions for writing strings etc that you have used in various tutorials ,

  • By BRAJESH - Reply

    @ Avinash Sir :
    I am using ATMEGA32A for USART communication but I am not successful due to getting unexpected character ie if I am transmitting ‘A’ then on the hyper terminal it is showing something different character even if I am using 16 MHz crystal osc.

    I am very greatful if any one help me on this issue….

    please any one help me what is problem..
    I am setting fuse bit for external osc 0x99EF
    and using same code as you used here….
    please help me I am struggling….:(

  • By Cesar Troya - Reply

    Hi, can you tell me please what software are you suing for the code that you post??? is AVR-Studio ? Win-Avr?

  • By Swapnil - Reply

    Hello Ashish,
    I have used Atmega32 running @ 7.3728Mhz and calculated UBBR is 23 for 19200 rate
    But still m getting special character on screen.
    Please Help.

  • By Rakesh Menon - Reply

    first of all,
    hats off to your hard work,

    i need a little explanation for your code in usart rx isr function,I analyzed and couldn’t understand a few statements,

    if(((UQEnd==RECEIVE_BUFF_SIZE-1) && UQFront==0) || ((UQEnd+1)==UQFront))
    /*you checked whether queue is full*/
    //Q Full
    /*i suppose,you deleted an element from buffer here as queue is full*/
    if(UQFront==RECEIVE_BUFF_SIZE) UQFront=0;
    /*I didn’t understand the purpose of above line*/

    /*here you have deleted all the elements from queue*/

    URBuff[UQEnd]=data;/*here you’ve en-queued an element*/
    if(UQFront==-1) UQFront=0;
    /*i didn’t understand purpose of this above statement*/

    please explain to me the statements I’ve mentioned as /*cannot understand*/,
    whenever you are free to help.
    thank you

    • By Avinash - Reply

      @Rakesh Menon

      Because you are not aware of a simple data structure called QUEUE in computer science!

      It is not in the scope of this tutorial.

      Its like entering a physics graduation class and the sir starting with long division !

  • By johnson - Reply

    i have such confusing problem…
    i use ATmega32 and have an interface between computer and ATMEGA, but when i send any character from computer via serial port, ATMEGA just recognize it as “à” that’s Asci code is “224″…also i write a program that whenever ATmega received ‘b’ , it turns on a LED, but as i said before, ATMEGA just receives ‘à’ so it don’t turn LED on… then i change program in the way that do same work with ‘à’ and it worked!… means that ATMEGA receives every character as ‘à’ but just when received Asci code is 224 (‘à’) it turns LED on…
    it is really confusing….can somebody help me?

  • By nidhi - Reply

    hi.. what shoud i do if i want to send a character using USART and display a ASCII value of that character on the hyperterminal ?

    • By Avinash - Reply


      This is no where related to programming or embedded system problem. But rather a simple logical thinking skill is required.

      If you can pay, then I can provide ready made program.

  • By Gunakshi - Reply

    Dear Avinash,
    Thank you for the amazing tutorials you have been posting. These are the best help for anyone!
    Avinash, I need your help regarding this particular demo. I am using Atmega16 and have made the project with your given specifications. Now, when I run this on RealTerm the problem is the data received is gibberish symbols or fixed values irrespective of what I am sending..
    I have checked the USB-Rs232 is installed and visible on COM port & is updated.
    Please, could you help me with this.. :)

  • By Gunakshi - Reply

    Hey Avinash,
    Thank you so much for your tutorials you have been posting. You have developed a brilliant website for all keen embedded learners.

    I am facing a problem with this demo. I have build your project with the same specifications on Atmega16 . But, whenever I send any character from my pc (using RealTerm) its receives some gibberish symbols back irrespective of the sent character.
    Please help me solve this problem..

  • By Miloni - Reply

    Hello Sir,

    I found your document useful.
    I have a problem in receiving the data from the bluetooth module. I have connected the Tx, Rx pins to the USART of the ATMEGA32 microcontroller. Then from my mobile’s bluetooth, when i try to send data from my app, i do not receive it on hyperterminal. Please help me out.

  • By GOWTHAM - Reply

    Avinash ji u realy rock
    im learning things from ur post. even i dnt learn this much in my clg.
    thnx a looooooot.
    very easy nd practical.

    • By Avinash - Reply


      Thanks :-)

Leave a Reply

Your email address will not be published. Required fields are marked *

× seven = 49

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>