Post on 04-Apr-2018
7/29/2019 67436110 RS232 Communication Using PIC18F4520 s USART PIC Micro Controller Tutorial eXtreme Electronics
1/24
Home
Home
Atmel AVR Tutorials
Introduction
Getting Started
Making Programmer and Development Board
Making Hello World Project
Digital Input/Output in AVRs
Interfacing Seven Segment Displays
Controlling DC Motors
Working with LCD Modules
Using Internal Peripherals
Analog To Digital Convertor
Introduction To AVR Timers
Timers in Compare Mode
Multiplexed Seven Segment Displays
Interfacing Temperature Sensor LM35
RS232 Communication Basics
RS232 Level Convertor
Using AVR USART
Serial I/O
More ...
Products
Low Cost AVR Dev Board
Microchip PIC Dev Board
xBoard MINI v2.0 (ATmega8)
xBoard v2.0 (ATmega16)
USB AVR Programmer
USB PIC Programmer
USB 8051 Programmer
More ...
Online Store
Forum
Links
Contact Us
Enquiry Form
Payment
May-11th-2010
RS232 Communication using PIC18F4520s USART PIC Microcontroller Tutorial
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
LCD Module DisplayISO 9001 Sunlike Design&Manufactue LCD Modules with high-quality.www.lcd-modules.com.tw
RS232 Realt im e Analyzer
For Windows / Linux. See what pure software solutions cannot show!
www.iftools.com
Programmable 5 .7" OEM GUI Ultra-bright, QVGA TFT LCD w/ touch x86 SBC, IO, program in C. $379+www.tern.com
NEW 32-bit Ard boardArd Compatible Hardware Buy Pic32 boards from Digilent.www.digilentinc.com/chipKIT
32 Communication using PIC18F4520's USART - PIC Microcontrol... http://extremeelectronics.co.in/microchip-pic-tutorials/rs232-communic...
24 8/4/2011 10:24 PM
7/29/2019 67436110 RS232 Communication Using PIC18F4520 s USART PIC Micro Controller Tutorial eXtreme Electronics
2/24
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 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.
RS232 Communication Basics.
RS232 Communication - The Level Conversion.
So basically we have a setup like this.
32 Communication using PIC18F4520's USART - PIC Microcontrol... http://extremeelectronics.co.in/microchip-pic-tutorials/rs232-communic...
24 8/4/2011 10:24 PM
7/29/2019 67436110 RS232 Communication Using PIC18F4520 s USART PIC Micro Controller Tutorial eXtreme Electronics
3/24
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 levelconverter. The following image show the serial port with built in level converter of40 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.
32 Communication using PIC18F4520's USART - PIC Microcontrol... http://extremeelectronics.co.in/microchip-pic-tutorials/rs232-communic...
24 8/4/2011 10:24 PM
7/29/2019 67436110 RS232 Communication Using PIC18F4520 s USART PIC Micro Controller Tutorial eXtreme Electronics
4/24
40PIN PIC Development board from eXtreme Electronics India.
Schematic for Testing Serial Communication with PIC18F4520
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.
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.
1.
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.
2.
32 Communication using PIC18F4520's USART - PIC Microcontrol... http://extremeelectronics.co.in/microchip-pic-tutorials/rs232-communic...
24 8/4/2011 10:24 PM
7/29/2019 67436110 RS232 Communication Using PIC18F4520 s USART PIC Micro Controller Tutorial eXtreme Electronics
5/24
The level converter: Converts between RS232 to TTL and vice-versa. Explained in more detailed way here ->
RS232 Communication - The Level Conversion
3.
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.
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.
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.
Hello world project with pic microcontroller part-i
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.
32 Communication using PIC18F4520's USART - PIC Microcontrol... http://extremeelectronics.co.in/microchip-pic-tutorials/rs232-communic...
24 8/4/2011 10:24 PM
7/29/2019 67436110 RS232 Communication Using PIC18F4520 s USART PIC Micro Controller Tutorial eXtreme Electronics
6/24
Right Click On Source File Section
And Select "Add Files ..." option
After that create a new file using menu optionFile->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 selectRebuildfromProject menu. If everything was OK the compilation will succeed and you will geta HEX file ready to burn into you MCU. Please see the following article for more info.
Hello world project with pic microcontroller part-i
32 Communication using PIC18F4520's USART - PIC Microcontrol... http://extremeelectronics.co.in/microchip-pic-tutorials/rs232-communic...
24 8/4/2011 10:24 PM
7/29/2019 67436110 RS232 Communication Using PIC18F4520 s USART PIC Micro Controller Tutorial eXtreme Electronics
7/24
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
#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(" ");
32 Communication using PIC18F4520's USART - PIC Microcontrol... http://extremeelectronics.co.in/microchip-pic-tutorials/rs232-communic...
24 8/4/2011 10:24 PM
7/29/2019 67436110 RS232 Communication Using PIC18F4520 s USART PIC Micro Controller Tutorial eXtreme Electronics
8/24
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 ");
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
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
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 someothers 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.
32 Communication using PIC18F4520's USART - PIC Microcontrol... http://extremeelectronics.co.in/microchip-pic-tutorials/rs232-communic...
24 8/4/2011 10:24 PM
7/29/2019 67436110 RS232 Communication Using PIC18F4520 s USART PIC Micro Controller Tutorial eXtreme Electronics
9/24
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
32 Communication using PIC18F4520's USART - PIC Microcontrol... http://extremeelectronics.co.in/microchip-pic-tutorials/rs232-communic...
24 8/4/2011 10:24 PM
7/29/2019 67436110 RS232 Communication Using PIC18F4520 s USART PIC Micro Controller Tutorial eXtreme Electronics
10/24
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.
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 . 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.
http://realterm.sourceforge.net/
Start Realterm from its Desktop Icon. You will get a screen similar to this. Increase the Value ofRow to 40 to see whole
message.
32 Communication using PIC18F4520's USART - PIC Microcontrol... http://extremeelectronics.co.in/microchip-pic-tutorials/rs232-communic...
f 24 8/4/2011 10:24 PM
7/29/2019 67436110 RS232 Communication Using PIC18F4520 s USART PIC Micro Controller Tutorial eXtreme Electronics
11/24
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
32 Communication using PIC18F4520's USART - PIC Microcontrol... http://extremeelectronics.co.in/microchip-pic-tutorials/rs232-communic...
f 24 8/4/2011 10:24 PM
7/29/2019 67436110 RS232 Communication Using PIC18F4520 s USART PIC Micro Controller Tutorial eXtreme Electronics
12/24
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 besent or received. Call it at the program startup.
Return Value: None
Parameters: None
32 Communication using PIC18F4520's USART - PIC Microcontrol... http://extremeelectronics.co.in/microchip-pic-tutorials/rs232-communic...
f 24 8/4/2011 10:24 PM
7/29/2019 67436110 RS232 Communication Using PIC18F4520 s USART PIC Micro Controller Tutorial eXtreme Electronics
13/24
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: NoneParameters: C Style NULL terminated string.
void USARTWriteInt(int val,unsigned char field_length)
This function is used for sending integer values. The second parameterfield_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 parameterfield_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.
32 Communication using PIC18F4520's USART - PIC Microcontrol... http://extremeelectronics.co.in/microchip-pic-tutorials/rs232-communic...
f 24 8/4/2011 10:24 PM
7/29/2019 67436110 RS232 Communication Using PIC18F4520 s USART PIC Micro Controller Tutorial eXtreme Electronics
14/24
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
USART Library for PIC18 (HI-TECH C).
Complete USART Demo Project with HI-TECH C and MPLAB for PIC18F4520
USART Demo HEX file for PIC18F4520
By
Avinash Gupta
May 11, 2010
1
0
This entry was posted on Tuesday, May 11th, 2010 at 9:44 am and is filed under Microchip PIC Tutorials. You can follow any responses to this
entry through the RSS 2.0 feed. You can leave a response, or trackbackfrom your own site.
22 Responses to RS232 Communication using PIC18F4520s USART PIC Microcontroller Tutorial
1
Angel.lee Says:
1.
Share
ShareShare
32 Communication using PIC18F4520's USART - PIC Microcontrol... http://extremeelectronics.co.in/microchip-pic-tutorials/rs232-communic...
f 24 8/4/2011 10:24 PM
7/29/2019 67436110 RS232 Communication Using PIC18F4520 s USART PIC Micro Controller Tutorial eXtreme Electronics
15/24
hello,my friend .
This is the first time to this Wedsite.
Your article write very well and easy to learn.
Thank you!
I am a beginner of PIC18F4520 MCU, and I am familiar with Pic16F877A.
I downloaded your code , use the same setup ReakTerm and the same MCU, but I got all (0)zero in the expriment.
CRYSTAL Frequency: 11.0592MHz
void USARTInit()
{
//Baud Rate = 57600 Bits per Second
//*** Note: Valid On 20MHz Crystal ONLY ***
//For other crystal freq calculate new values for SPBRG
SPBRG=47;
//TXSTA REG
TXEN=1;
BRGH=1;
//RCSTA
SPEN=1;
CREN=1; //Enable Receiver (RX)
//BAUDCON
BRG16=1;
}
The other code is the same with you .
Can you tell me what goes wrong?
May 12th, 2010 at 9:04 am
2
Avinash Says:
@Angel,
Which programmer did you used to program the chip?
Did you write the configuration bits? They are important for setting up the appropriate clock source.
The configuration bits are embedded in souce file and after compilation they are transferred to the HEX file the
programmer then MUST read those and program at appropriate locations!
Try changing the crystal to 20Mhz instead of 11.0592
May 12th, 2010 at 9:23 am
2.
3
Angel.lee Says:
My programmer is HI-TECH C PRO for the PIC18 MCU Family V9.63PL3
And MPLAB IDE v8.10.
ha, I got it just now.
I forgot the configuration bits.
Now it goes well.
Thank you very much.
Can I ask which country are you from? I am from China.
May 12th, 2010 at 11:23 am
3.
4Angel.lee Says:
@Avinash,
I met another problem ,I am sorry!
4.
32 Communication using PIC18F4520's USART - PIC Microcontrol... http://extremeelectronics.co.in/microchip-pic-tutorials/rs232-communic...
f 24 8/4/2011 10:24 PM
7/29/2019 67436110 RS232 Communication Using PIC18F4520 s USART PIC Micro Controller Tutorial eXtreme Electronics
16/24
I changed the baud rate to 9600 by set:
SPBRG=0x1F;
SPBRGH=001;
BRGH=1;
BRG16=1;
but the MCU didnt work again.
I changed the baud rate back to 57600 again, it works.
why? I cannot anderstand.
May 12th, 2010 at 11:59 am
5
Avinash Says:
@Angel.lee
I am from India
May 13th, 2010 at 11:46 am
5.
6
Introduction to PIC18's Timers - PIC Microcontroller Tutorial | eXtreme Electronics Says:
[...] The circuit is described in this article. [...]
May 13th, 2010 at 12:38 pm
6.
7
Thilini Says:
When I compiled the above code for PIC16F877a , the following errors are coming,
Licensed for evaluation purposes only.
This licence will expire on Thu, 29 Jul 2010.
HI-TECH C Compiler for PIC10/12/16 MCUs (PRO Mode) V9.70
Copyright (C) 2009 Microchip Technology Inc.
Error [1346] ; 0. cant find 05 words for psect config in segment CONFIG (largest unused contiguous range
01)Error [500] ; 0. undefined symbols:
_USARTReadByte(pwnw.obj) _USARTWriteInt(pwnw.obj) _USARTInit(pwnw.obj) _USARTWriteByte(pwnw.obj)
_USARTWriteString(pwnw.obj) _USARTWriteLine(pwnw.obj)
********** Build failed! **********
Can u pls help me.
June 12th, 2010 at 12:50 pm
7.
8
Avinash Says:
@Thilini,
NO I cannot help as you dont know how to read!
Cant you read the the program is ment for a PIC18 arch ??? So why compiling for PIC16 arch ???
June 13th, 2010 at 7:58 am
8.
9
Look4tech.com RS232 Communication using PIC18F4520s USART PIC Microcontroller Tutorial Says:
[...] more at extremeelectronics.co.in Leave a comment | Trackback Comments are closed. Theme Styles [...]
September 18th, 2010 at 1:49 pm
9.
32 Communication using PIC18F4520's USART - PIC Microcontrol... http://extremeelectronics.co.in/microchip-pic-tutorials/rs232-communic...
f 24 8/4/2011 10:24 PM
7/29/2019 67436110 RS232 Communication Using PIC18F4520 s USART PIC Micro Controller Tutorial eXtreme Electronics
17/24
10
Interfacing RFID Reader with AVR MCUs - AVR Tutorial | eXtreme Electronics Says:
[...] We have a nice collection of beginner friendly tutorials on RS232 and USART on both Atmel AVRs and PIC
[...]
September 20th, 2010 at 7:53 pm
10.
11
saif Says:
what changes have to be made for 16f877?
September 22nd, 2010 at 1:03 am
11.
12
Avinash Says:
@Saif,
PIC16 and PIC18 are different arc! You have to change compiler and other things.
Better change to PIC18 arch as they are high end & perfect for scalable design where cost isnt any matter.
September 22nd, 2010 at 9:46 am
12.
13
Introduction to PIC Interrupts and their Handling in C | eXtreme Electronics Says:
[...] them. So the CPU keeps on doing its normal job unless and interrupt occurs. For example when the USART
(Serial Communication Hardware) will receive data is unknown, it can receive data any time. So the [...]
December 5th, 2010 at 10:51 am
13.
14
beginner Says:
aoa! nice article! could we use the same connection of pic to communicate to a mobile phone(gsm modem) which
supports serial interface with rs232?in that case how would we check the data that is transmitted or received?whatwould be the format?
December 16th, 2010 at 4:43 am
14.
15
Johan Says:
Hello
Great Tutorial !
One question though, if i have a lot of other activities like turning on LEDS and scanning buttons and i am doing
this in the main loop where i am also using USARTReadbyte().
Can i loose some messages then ?
As i understand it i must poll the USARTReadbyte() with a high frequency or am i wrong ?
Best RegardsJohan Nilsson
February 8th, 2011 at 6:45 pm
15.
16
Avinash Says:
@Johan,
Good question. If we were doing something else while a byte arrived at USART then it will buffer it, but ifwe were still busy and another byte come in the first one will be lost. To over come this problem we need towrite an ISR to handle USART events. As soon as data arrives USART jumps to this ISR which buffers the
data in a FIFO queue. This FIFO may have a length of say 64 or 128 byte (depending upon how much RAMyou can dedicate to this purpose). Latter application main polling loop when comes to the point where itchecks how much data is on queue. It retrieve and process each of them.
This tutorial was a basic intro to PIC USART so I didnt used Interrupts and FIFO buffers.
16.
32 Communication using PIC18F4520's USART - PIC Microcontrol... http://extremeelectronics.co.in/microchip-pic-tutorials/rs232-communic...
f 24 8/4/2011 10:24 PM
7/29/2019 67436110 RS232 Communication Using PIC18F4520 s USART PIC Micro Controller Tutorial eXtreme Electronics
18/24
February 9th, 2011 at 8:31 am
17
zick Says:
Hi,
im using interrupt for receiving data. Its working fine. But how to receive a string data using interrupt. Ive
problem with timing, where data received , I stored it a t buffer, but the moment I try to store data, I got another
coming..and again..and again. I lost some of the data due to this routine. Do you have any idea how to solve string
data received using interrupt. If you can give some code example, Im really appreciated .Thanks
February 12th, 2011 at 1:09 pm
17.
18
Devendran Says:
Hi There,
The internet is truly wonderful knowledge sharing such as what you have demonstrated. Thank you for sharing
I am looking to develop an ethernet to multiple RS232(max of 51) project, and plan to use a PIC 32 for the
ethernet service, and have slaves of PIC18s to handshake RS232 comm. I was wondering if you have come
accross such a solution before?
April 20th, 2011 at 4:03 pm
18.
19
Megha10 Says:
Hi, will this uart communication code work with pic18f6527? I further require this microcontroller to drive a Lin
transceiver.Any suggestion on writing the code for LIN communication or any forum which gives it?
May 27th, 2011 at 6:28 pm
19.
20
Reiner Beh Says:
Hello my friend, I am new with programming PICs. With RENESAS-CPUs Im very confident. But now my greatproblem. I have to transmit and receive data per EUSART2 of PIC18F46J50 and this although per INTERRUPT.
Receiving data per INT is OK that functioned. Transmitting data per polling is although no problem, everithing is
OK. But transmitting data by interrupt will not function. What Im doing wrong here ??? This is my code:
//These are my actual interrupt handling routines.
#pragma interrupt YourHighPriorityISRCode
void YourHighPriorityISRCode()
{
#if defined(EUSART2_INTERRUPT_RX) // definiert in uart.h
// EUSART2_INTERRUPT-Receive bearbeiten
UART_Rx();
#endif // EUSART2_INTERRUPT_RX
#if defined(EUSART2_INTERRUPT_TX) // definiert in uart.h
// EUSART2_INTERRUPT-Transmit bearbeiten
UART_Tx();
#endif // EUSART2_INTERRUPT_TX
}
void main(void)
{
// I/O states will be held until DSCONL.RELEASE = 0, but we must still initialize
// to what we want before clearing the RELEASE bit.
InitializeSystem(); // calling some init-routines and
// InitUART(BAUD_19200,
// DATABITS_8,
// STOPPBITS_1, // not used
20.
32 Communication using PIC18F4520's USART - PIC Microcontrol... http://extremeelectronics.co.in/microchip-pic-tutorials/rs232-communic...
f 24 8/4/2011 10:24 PM
7/29/2019 67436110 RS232 Communication Using PIC18F4520 s USART PIC Micro Controller Tutorial eXtreme Electronics
19/24
// PARITY_NONE, // not used
// FALSE);
INTCONbits.GIE = 1; // Interrupting enabled.
while(1) {
// check Rx-data
UART_CheckRxData();
MAIN_Wait(10, 10); // ~ 10 ms
// execute UART-functions
// transmit data per Interrupt
if (uiTest_State == 0) {
uiTest_State = 1;
// length of Tx-data in byte
stUART_Data.uiTxDataLength = 1;
// pointer to Tx-data
stUART_Data.pcTxData = (char*)&cTest_TxData[1];
stUART_Data.boolTxData = TRUE;
// write first char then go on per interrupt
Write2USART(cTest_TxData[0]);
}
} // while(1)
}
void Open2USART_Ext( unsigned char config, unsigned int spbrg)
{
TXSTA2 = 0; // Reset USART registers to POR state
RCSTA2 = 0;
if(config&001) // Sync or async operation
TXSTA2bits.SYNC = 1;
if(config&002) // 8- or 9-bit mode
{
TXSTA2bits.TX9 = 1;
RCSTA2bits.RX9 = 1;
}
if(config&004) // Master or Slave (sync only)
TXSTA2bits.CSRC = 1;
if(config&008) // Continuous or single reception
RCSTA2bits.CREN = 1;
else
RCSTA2bits.SREN = 1;
if(config&010) // Baud rate select (asychronous mode only)
TXSTA2bits.BRGH = 1;
else
TXSTA2bits.BRGH = 0;
if(config&020) // Address Detect Enable
RCSTA2bits.ADDEN = 1;
// SENDB(asychronous mode only) need to be added
if(config&040) // Interrupt on receipt
PIE3bits.RC2IE = 1;
32 Communication using PIC18F4520's USART - PIC Microcontrol... http://extremeelectronics.co.in/microchip-pic-tutorials/rs232-communic...
f 24 8/4/2011 10:24 PM
7/29/2019 67436110 RS232 Communication Using PIC18F4520 s USART PIC Micro Controller Tutorial eXtreme Electronics
20/24
else
PIE3bits.RC2IE = 0;
if(config&080) // Interrupt on transmission
PIE3bits.TX2IE = 1;
else
PIE3bits.TX2IE = 0;
SPBRG2 = spbrg; // Write baudrate to SPBRG2
SPBRGH2 = spbrg >> 8; // For 16-bit baud rate generation
TXSTA2bits.TXEN2 = 1; // Enable transmitter
RCSTA2bits.SPEN = 1; // Enable receiver
}
void InitUART(unsigned char ucBaud, unsigned char ucData,
unsigned char ucStopp, unsigned char ucParity,
BOOL boolDspMsg)
{
UART_InitData();
stUART_Para.boolActiv = FALSE;
// Open the USART configured as
// 8N1, 2400 baud, in polled mode (f = 4 MHz)
Open2USART_Ext (USART_TX_INT_ON & // Tx-Int ON
USART_RX_INT_ON & // Rx-Int ON
USART_ASYNCH_MODE & // asynchron mode
ucData & // databits
USART_CONT_RX & // continuous reception
USART_BRGH_HIGH, // high speed mode
ucBaud); // baudrate
UART_Wait(10, 10); // ~ 10 ms OK
// SchnittstellenParameter UART0
stUART_Para.ucVal_Baud = ucBaud;
stUART_Para.ucVal_Databits = ucData;
stUART_Para.ucVal_Stoppbits = ucStopp;
stUART_Para.ucVal_Parity = ucParity;
// Enable interrupt priority
RCONbits.IPEN = 1;
// Make receive interrupt low priority : 0
// Make receive interrupt high priority : 1IPR3bits.RC2IP = 1; // EUSART2 Rx : high priority
TXSTA2bits.TXEN = 1;
_asm
NOP
NOP
_endasm
// Make transmit interrupt low priority : 0
// Make transmit interrupt high priority : 1
// IPR3bits.TX2IP = 0; // EUSART2 Tx : low priority
IPR3bits.TX2IP = 1; // EUSART2 Tx : high priority
// Enable all low priority interrupts
INTCONbits.GIEL = 1;
}
32 Communication using PIC18F4520's USART - PIC Microcontrol... http://extremeelectronics.co.in/microchip-pic-tutorials/rs232-communic...
f 24 8/4/2011 10:24 PM
7/29/2019 67436110 RS232 Communication Using PIC18F4520 s USART PIC Micro Controller Tutorial eXtreme Electronics
21/24
Sorry, but some function-code is not complete, but I hope that one can understand what I want to do
The problem is, when I call the UART-Function => Open2USART_Ext() to initialize EUSART2 with
USART_TX_INT_ON the program does not reach the main-routine after calling => InitializeSystem().
But when I call the UART-Function => Open2USART_Ext() to initialize EUSART2 with USART_TX_INT_OFF
the program function normally, but only with sending data without interrupt !!!
Can you please help me ???
Thank you for your fast reply !
Many Thanks Reiner
June 4th, 2011 at 8:35 pm
21
Cavalcade of Mammals Blog Archive Links for June 2011 Says:
[...] Picprog, programmer software for PIC microcontrollers Serial interface using MAX232 [...]
June 7th, 2011 at 4:17 am
21.
22
naseem Says:
thanks a lot & god save you
June 9th, 2011 at 4:07 pm
22.
Leave a Reply
Name (required)
Mail (will not be published) (required)
Website
Notify me of followup comments via e-mail
New ProductsTags
Meta
New Products
32 Communication using PIC18F4520's USART - PIC Microcontrol... http://extremeelectronics.co.in/microchip-pic-tutorials/rs232-communic...
f 24 8/4/2011 10:24 PM
7/29/2019 67436110 RS232 Communication Using PIC18F4520 s USART PIC Micro Controller Tutorial eXtreme Electronics
22/24
Tags
development boardUARTMultiplexingcxBoardusb pic programmerisrusbRFIDSerialPIC Development Boardsensor
atmegapic programmerinterruptmcuRoboticspic tutorialks0108pic16fmplabProGFXpic16f877Timeriratmega16atmega8Seven SegmentpwmADChi-tech cglcdgraphic lcdpic18f
pic18f4520rs232microchipUSARTatmega32pic18f2550pic18f4550lcdpic18
AVRpic
Meta
Log in
RSS
Comments RSS
WordpressValid XHTML
Recent Post
Comments
Video
Recent Post
Got the TFT LCD + STM32F103VE MCU Up and Running !
Working with Images in ProGFX
Thermometer with PIC Microcontroller
Rs. 300 Off on GLCD Development Board !
Visualize ADC data on PC Screen using USART AVR Project
Using Multiplexed 7 Segment Displays PIC Microcontroller Tutorial
Using Shift Registers with AVR Micro AVR Tutorial
Our New Shipping Boxes !
AVR RGB LED and Sound Show
Stepper Motor Control AVR Tutorial
Comments
Ronaldo: can you change the pin mapping for atemga323L for this configuration, if yes, how download...
Dario: im using atmega324pBinu: Whats the BASIC compiler you are using for ARM Micros?
Ronaldo: @Ronaldo, Please also specify the MCU like ATmega128? Also if you are using some kind of...
Sam: I have a better understanding of PWM now. Looking forward to the next tutorial where I could...
Sam: An excellent intro to PWM. Thanks for the good work.
32 Communication using PIC18F4520's USART - PIC Microcontrol... http://extremeelectronics.co.in/microchip-pic-tutorials/rs232-communic...
f 24 8/4/2011 10:24 PM
7/29/2019 67436110 RS232 Communication Using PIC18F4520 s USART PIC Micro Controller Tutorial eXtreme Electronics
23/24
Dario: ds_077@hotmail.com
Video
Categories
AVR Development Board
AVR Projects
AVR Tutorials
Chitchat
Code Libraries
Code Snippets
electronicsHardwares
Microchip PIC Tutorials
News
PIC Development Board
Programming in 'C'
RF
Robotics
Software
Tools
NavigationHome
Forum
Shop
Links
Subscribe
Get New Articles Deliverd To Your Inbox!
Email address:
Ads by Google
Microcontroller Projects
8051 Microcontroller
Microcontroller C
AVR Microcontroller
Ads by Google
Microcontroller PWM
RS232 Serial Interface
DMX PC Interface
Microcontroller Kits
32 Communication using PIC18F4520's USART - PIC Microcontrol... http://extremeelectronics.co.in/microchip-pic-tutorials/rs232-communic...
f 24 8/4/2011 10:24 PM
7/29/2019 67436110 RS232 Communication Using PIC18F4520 s USART PIC Micro Controller Tutorial eXtreme Electronics
24/24
Delivered by FeedBurner
Comments
Ronaldo: can you change the pin mapping for atemga323L for this configuration, if yes, how download...
Dario: im using atmega324p
Binu: Whats the BASIC compiler you are using for ARM Micros?
Ronaldo: @Ronaldo, Please also specify the MCU like ATmega128? Also if you are using some kind of...
Sam: I have a better understanding of PWM now. Looking forward to the next tutorial where I could...
Sam: An excellent intro to PWM. Thanks for the good work.
Dario: ds_077@hotmail.com
eXtreme Electronics 2008-2011 | See Our Privacy Policy
32 Communication using PIC18F4520's USART - PIC Microcontrol... http://extremeelectronics.co.in/microchip-pic-tutorials/rs232-communic...