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

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.

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.

good pic development board

good pic development board with serial

40PIN PIC Development board from eXtreme Electronics India.

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

You will also need a serial cable to connect the board and PC. It can be easily made with the help of two DB9 Female connector and a three conductor cable.

rs232 cable

Connecting PIC Board and PC

If you are using the 40 PIN Devboard from eXtreme Electronics then use the above wiring scheme. Otherwise if you are using the schematic provided in this tutorial use the wiring scheme given below.

 

rs232 cross cable

Connecting PIC Board and PC

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
Interrupts.

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
www.eXtremeElectronics.co.in

                     NOTICE
                  -------------
NO PART OF THIS WORK CAN BE COPIED, DISTRIBUTED OR PUBLISHED WITHOUT A

WRITTEN PERMISSION FROM EXTREME ELECTRONICS INDIA. THE LIBRARY, NOR ANY PART
OF IT CAN BE USED IN COMMERCIAL APPLICATIONS. IT IS INTENDED TO BE USED FOR
HOBBY, LEARNING AND EDUCATIONAL PURPOSE ONLY. IF YOU WANT TO USE THEM IN 
COMMERCIAL APPLICATION PLEASE WRITE TO THE AUTHOR.

*****************************************************************/

#include <htc.h>

#include "usart.h"

//Chip Settings
__CONFIG(1,0x0200);
__CONFIG(2,0X1E1F);
__CONFIG(3,0X8100);
__CONFIG(4,0X00C1);
__CONFIG(5,0XC00F);


void main()
{
   //Initialize the USART
   USARTInit();

   //Write Some line of TEXT
   USARTWriteLine("********************************");
   USARTWriteLine(" ");
   USARTWriteLine("        GOD IS GREAT !!!");
   USARTWriteLine(" ");
   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): ");
   USARTWriteInt(782,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

   while(1)
   {
      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>

      USARTWriteByte('<');
      USARTWriteByte(data);
      USARTWriteByte('>');

   }
}

Setting Up Hyperterminal and using it to communicate with PIC18F4520

If you are using Windows XP start HyperTerminal Program. Its Found under Communication Folder inside the Accessories Menu (which is itself inside Start Menu->All Programs).

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

hypertermical setup for pic18f4520

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 PIC MCU and wont get expected results.

hyperterminal setup for pic18f4520

Select COM Port

Now setup the COM port parameters as follows.

  • Bits per second: 57600
  • 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! Connect the PIC Development board by using a serial cable to PCs COM port and switch on the board. If everything went right HyperTerminal and PIC will talk happily and PIC will send the following message as we have programmed it.

hyperterminal and PIC talking

Screenshot of Hyperterminal Showing the message received from PIC18F4520

If the screen shows similar message then you have successfully created a link between PC and your PIC micro. It shows that PC can read the data sent by PIC18F4520. To test if the PIC can also read Hyperterminal, press some keys on PC keyboard. Hyperterminal will send them over COM port to the PIC mcu where PIC will process the data. In the simple test program this processing including returning the same data but enclosed inside < and >, so if you press a then PIC will return <a>. If you are able to see this on PC screen then you are sure that PIC 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 PIC18F4520

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.

realterm and pic18f4520

Screenshot of Realterm Showing the message received from PIC18F4520

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

 

Screenshot of Realterm Setup

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

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.

Example

USARTWriteByte('a');

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.

Example

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

USARTWriteInt(99,4)

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

0099

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

99

  • 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

Example

char data;
data=USARTReadByte();

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.

Downloads

By
Avinash Gupta

May 11, 2010