Hello Friends! In this tutorial I will discuss how to practically do a simple communication over RS232 interface. For those who are completely new to this I clarify that the motive is to send and receive data between two device using a standard called RS232. RS232 is serial interface that means that data is transferred BIT by BIT at a time. Since data is transferred BIT by BIT so we need only a single wire two send data and an another one to receive data. One more common wire (called GND) is required between two separate circuit to enable current flow. So a total of three wire are required for communication.

RS232 can be used to communicate between a variety of devices. Like your MCU and a GSM module or a PC. In this tutorial we will demonstrate a link between a PIC18F4520 MCU and a standard PC. On PC we will run a terminal program like RealTerm or Hyperterminal. A terminal program is used to send and receive text data. So any text send by the MCU will be visible on Terminal Screen and Any keypress you make on the PC keyboard will be send over RS232 to your MCU. This configuration is the simplest setup to test and understand RS232 communication. When you have enough knowledge you can replace the Terminal with your own PC end software for sending receiving data.

RealTerm Terminal Program

Realterm Terminal Program Displaying the data received from PIC18F


The same functions that we use here to communicate with PC can be used to send/receive data to/from other devices also. But note one thing that modern PCs don’t have a serial port so you need to buy a USB to serial converter. They are available easily at low cost. You can purchase one from our online store.

USB to Serial Adapter

Fig. USB to Serial Converter


I recommend you to read and understand the following articles before proceeding.

So basically we have a setup like this.

Connecting PIC18F4520 with a PC

Connecting PIC18F4520 with a PC.

In Serial Communication the line that is used to transmit data is called Tx and the line used to receive data is called Rx. The PIC MCU uses TTL level for logic that is a 1 is a 5v and 0 is 0v but RS232 standard uses different scheme for logic level, so we need a level converter in between. The article that describes how to make a level converter is here RS232 Communication – The Level Conversion.

Now the data is ready to be fed to a standard serial port of PC. All good development board has an on board level converter. The following image show the serial port with built in level converter of 40 PIC PIC development board. The MAX232 IC that you can see is industry standard chip for the purpose of level conversion between RS232 and TTL signals.

PIC40 Development Board

Fig. DB9 Female on PIC 40 PIN Development Board


Images below shows how easy it is to connect a USB to Serial Converter to the board.

PIC Dev Board USB to Serial

Fig. Connecting with Serial Port


PIC Dev Board Serial Communication

Fig. Serial Port Connected


Schematic for Testing Serial Communication with PIC18F4520

pic18f4520 usart test shcematic

PIC18F4520 USART Test Schematic

The above image show the schematic of circuit you will need to make. Most of the circuit is common for many other application too. The only specific part is the level converter which built around the MAX232 IC. I am explaining in short the parts and their functions.

  1. Power Supply unit : This part is required in all project. It is built around LM7805 IC. The function of this unit is to provide a regulated 5v supply to other units. I have used a 1N4007 diode to protect this unit from reverse voltage. Even if by mistake you supply wrong polarity the thing wont blow away. For convenience I have also included a LED which will indicate that power supply unit is working OK.
  2. MCU core: The heart of this unit is PIC18F4520 chip (you may also use PIC18F4550). The ICSP connector is used to download programs via a PIC programmer. RESET switch is used to reset the MCU so its start executing from the beginning of the program. A 20MHz crystal is the source of oscillation. C12 and C6 which are 0.1uF (Marking 104) should be placed as closed to the MCU as possible, they provide extra immunity to noise.
  3. The level converter: Converts between RS232 to TTL and vice-versa. Explained in more detailed way here -> RS232 Communication – The Level Conversion


Program in HI-TECH C and MPLAB for PIC18F4520

For most of my project I use MPLAB along with HI-TECH C. If you are new to these tools please read the following article. It discuss in details how to obtain, setup and use these tools.

Create a new folder say usart_test in your hard disk. Copy following files to it. You can get those file from the download link at the bottom of this article.

  • usart.c
  • usart.h

Open MPLAB and create a new project as described here. Now add the "usart.c" file to the "Source Files" section and "usart.h" to the "Header Files" section. To add any file to "Source Files" section right click on "Source Files" in Project window and select "Add Files …" command. Then go the the project folder you just created and select the file.

adding files to mplab

Right Click On Source File Section


adding files to mplab

And Select "Add Files …" option

After that create a new file using menu option File->New and save it by name usart_test.c . Make sure that "Add File to Project" is selected during saving. Now copy/paste the following program in this new file and save it. To compile and build this project select Rebuild from Project menu. If everything was OK the compilation will succeed and you will get a HEX file ready to burn into you MCU. Please see the following article for more info.

The Hex file can be burnt to the PIC18F4520 MCU using any PIC programmer


Most Basic USART (RS232 Serial) Communication Demo.

Explains simple reading and writing of data without using

BAUD RATE:57600 Bits per Second
CRYSTAL Frequency: 20MHz

Target Chip: PIC18F4520
Target Compiler: HI-TECH C For PIC18 (http://www.htsoft.com/)
Project: MPLAP Project File

Author: Avinash Gupta
Copyright (c) 2008-2009
eXtreme Electronics, India




#include <htc.h>

#include "usart.h"

//Chip Settings

void main()
   //Initialize the USART

   //Write Some line of TEXT
   USARTWriteLine(" ");
   USARTWriteLine("        GOD IS GREAT !!!");
   USARTWriteLine(" ");
   USARTWriteLine("                     -USART Demo");
   USARTWriteLine("  -By eXtreme Electronics, India");
   USARTWriteLine("                 -For PIC18F4520");
   USARTWriteLine(" ");
   USARTWriteLine("Integer Printing Test ...");
   USARTWriteString("A positive integer: ");
   USARTWriteInt(99,255);  //No fixed field lenght i.e. 255

   USARTWriteLine(" ");

   USARTWriteString("A negative integer: ");
   USARTWriteInt(-24,255);  //No fixed field lenght i.e. 255
   USARTWriteLine(" ");

   USARTWriteString("An Integer with fixed field width(5): ");
   USARTWriteLine(" ");

   USARTWriteLine(" ");
   USARTWriteLine(" ");

   USARTWriteLine("Please type on PC Keyboard .....");
   USARTWriteLine("Any Character you type will be returned by MCU");
   USARTWriteLine("But enclosed inside < and >");
   USARTWriteLine("Eg. if you press a");
   USARTWriteLine("MCU will return <a>");
   USARTWriteLine("This tests that both Rx and Tx are working OK");

   //Now Read some input

      char data;

      data=USARTReadByte();   //Wait until a byte is available

      //Now Send the same byte but surrounded by < and >
      //like if user type 'a' we will send <a>



Setting Up Realterm

To interact with this demo running on your PIC development board. You need a terminal program. A terminal program is a utility tool running on PC that helps you view text data coming from the serial port and also send data to the port. This is handy for initial development of connected hardwares. It can be downloaded from here.

Start Realterm from its Desktop Icon.

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

  • Baud: 57600
  • Port: Port where you have connected the PIC
  • Data bits: 8
  • Parity: None
  • Stop bits: 1
  • Hardware Flow Control: None
RealTerm Terminal Program

Realterm Terminal Program Displaying the data received from PIC18F

After setting up Realterm, connect the PIC board with COM port and switch it on. You will receive a message on Realterm as shown above.

Once you receive this message, you can be sure that data is easily flowing from the PIC microcontroller to the PC. But now we also need to check if the data is able to reach the MCU from the PC or not.

For this, click on the top large black area of RealTerm and then press any key on the keyboard of your PC. RealTerm will send those data to MCU and if MCU is able to read those data, it will reply back with the same character but enclosed in a <>. That means if you press ‘a‘ on keyboard you will see <a> on the terminal window.

This confirms that MCU is also able to read data from the serial port.

Understanding the USART library for PIC18 Microcontroller

Here I have created a small library to work with USART. This keeps the USART code separate from the application code. The same library can be used in many other project that requires USART communication. The functions available in the library are discussed below.

void USARTInit()

This function initializes the internal USART of the PIC18F4520 microcontroller. This must be called before data can be sent or received. Call it at the program startup.

  • Return Value: None
  • Parameters: None

void USARTWriteByte(char ch)

Writes a byte of data to the USART.

  • Return Value: None
  • Parameters: data to be sent.



Will send character ‘a’ to the serial port.

void USARTWriteString(const char *str)

This function will send a string of character to the serial port.

  • Return Value: None
  • Parameters: C Style NULL terminated string.


USARTWriteString("Hello World !");

Will send the string "Hello World !" to the serial port. If you have Terminal Program Monitoring that port the message "Hello World !" will be displayed there.

void USARTWriteLine(const char *ln)

Same as the above function but after sending the string it takes the cursor to the beginning of the next line. So next string you send will be printed on new line. If you are working on a Linux based terminal it may now work! In Windows a new line is a CR/LF pair but in Linux it is different.

  • Return Value: None
  • Parameters: C Style NULL terminated string.

void USARTWriteInt(int val,unsigned char field_length)

This function is used for sending integer values. The second parameter field_length is the lenght of field. Integer can be printed in two ways. One is fixed field length and other is variable field length. In fixed field width you specify the width of field by the parameter field_length. In this case integer will always have this much digits. Leading zeros may be added. Say if you call


Then the width of the field will be constant i.e. 4 as passed. So the number will be printed like this


On the other hand variable width integer printing prints as much digit as their are in the original number. So a call like this

USARTWriteInt(99,255); //255 stands for variable width

will print


  • Return Value: None
  • Parameters: val = 16 bit signed integer, field_length= width of field required or 255 for variable width.

unsigned char USARTReadByte()

Wait until a byte is received from USART/Serial Port and return the value read from the USART.

  • Return Value: Byte read from USART
  • Parameters:None


char data;

Now the variable data has the byte received from the USART.

That’s the end of this tutorial. Hope you find it useful. If you have any suggestion do drop in a comment.

Finding the COM Port Number

On windows desktop right click on Computer Icon

Windows desktop
Windows Desktop

Select Properties from the context menu.

Computer Context Menu
Select Properties

This will open up system properties.

System Properties
System Properties

From the left hand side, select Device Manager as shown in the image above. It will open up the Device Manager

Device Manager
Device Manager

Expand the Ports (COM & LPT) node as shown in the image above. Find the Port Named Prolific USB-to-Serial Comm Port and note the number shown next to it in brackets.

In our case it is COM2 that’s why we have opened Port 2 in RealTerm

RealTerm COM2
Open Port 2 in Real Term

Important Note !

In order to use the USB to Serial Adapter, it’s driver must be installed correctly ! You can download the drivers from here.


Avinash Gupta

May 11, 2010


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

More Posts - Website

Follow Me:
FacebookLinkedInGoogle Plus