Transmitting and receiving data using UART protocol PIC Microcontroller

UART-protocol-pic-microcontroller

UART or serial communication is one of the important protocol used by the Microcontrollers to transmit and receive data from the external devices. Almost every controller is equipped with this protocol to make transmission and reception easier just using two pins. This tutorial will teach you to initialize and send data by using UART protocol PIC microcontroller.

I assume that you are familiar with the concept of UART and proceed to explain the steps to initialize and use it in PIC controller. If you are familiar with the concept of  UART kindly go through this link before proceeding.

REGISTERS USED IN UART:

TXSTA REGISTER: This register have the status and control bits of the Transmission in the controller.

RXSTA: This register holds the status and control bits of the Reception in the microcontroller.

SPBRG: This register holds the value which decides the baud rate of the serial communication. The formula governing the calculation varies based on the modes high speed and low speed.

LOW SPEED:

(Asynchronous) Baud Rate = FOSC/(64 (X + 1))

(Synchronous) Baud Rate = FOSC/(4 (X + 1))

HIGH SPEED:

Baud Rate = FOSC/(16 (X + 1))

Where X is the value of SPBRG register.

 

Since we are using standard 9600 bps, we are about to use 129 in the SPBRG register. According to the datasheet it results in giving 9600 bps 20MHZ crystal. You can find brief explanation of the bits in these registers in the data sheet of this controller.

CODE:

This code was built using PIC C compiler. The code was built in a way to transmit the word “SRT” through UART to the hyperterminal and then print the received bytes in the LCD.

#include <usart.h>
#byte lcd=0x06
#byte TRIS_lcd=0x86
#bit en=0x07.1
#bit rs=0x07.0
#bit TRIS_en=0x87.1
#bit TRIS_rs=0x87.0
#byte TXSTA=0x98
#byte RCSTA=0x18
#byte SPBRG=0x99
#byte TXREG=0x19
#bit TXIF=0x0c.4
#byte RXREG=0x1A
#bit RXIF=0x0c.5
char c;
void display(char a,int b)     //lcd subroutine
  {
    lcd=a;
    rs=b;
    en=1;
    delay_ms(100);
    en=0;
    delay_ms(100);
  }

void main()
  {
   TRIS_lcd=TRIS_rs=TRIS_en=0;
   display(0x38,0);
   display(0x01,0);
   display(0x0f,0);
   TXSTA=0x26;             //initializing transmission 
   RCSTA=0x90;            //Initializing reception
   SPBRG=129;             //Setting Baud rate
   TXREG='S';
   while(TXIF==0);      //Waiting for transmission flag to set
   TXREG='R';
   while(TXIF==0);
   TXREG='T';
   while(TXIF==0);
   while(TRUE)
      {
        while(RXIF==0);  //Waiting for reception flag to set
        c=RXREG;
        display(c,1);
      }
}

Leave a Comment

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