Monday 19 October 2015

PIC16F877A SERIAL COMMUNICATION




#include<pic.h>
#include<htc.h>
#define __PIC16F877A_H


__CONFIG( FOSC_HS & WDTE_OFF & PWRTE_ON & CP_OFF & BOREN_ON & LVP_OFF & CPD_OFF & WRT_OFF & DEBUG_OFF);



#define _XTAL_FREQ   20000000

void InitUART(void);
void SendByteSerially(unsigned char);
unsigned char ReceiveByteSerially(void);
void SendStringSerially(const unsigned char*);



void interrupt ISR(void)
{
if(RCIF)  // If UART Rx Interrupt
{
if(OERR) // If over run error, then reset the receiver
{
CREN = 0;
CREN = 1;
}

SendByteSerially(RCREG); // Echo back received char
}
}


void InitUART(void)
{
TRISC6 = 0;   // TX Pin
TRISC7 = 1;   // RX Pin

SPBRG = 129;
BRGH  = 1;                   // Fast baudrate
SYNC  = 0; // Asynchronous
SPEN  = 1; // Enable serial port pins
CREN  = 1; // Enable reception
SREN  = 0; // No effect
TXIE  = 0; // Disable tx interrupts
RCIE  = 1; // Enable rx interrupts
TX9   = 0; // 8-bit transmission
RX9   = 0; // 8-bit reception
TXEN  = 0; // Reset transmitter
TXEN  = 1; // Enable the transmitter
}


void SendByteSerially(unsigned char Byte)  // Writes a character to the serial port
{
while(!TXIF);  // wait for previous transmission to finish
TXREG = Byte;
}

unsigned char ReceiveByteSerially(void)   // Reads a character from the serial port
{
if(OERR) // If over run error, then reset the receiver
{
CREN = 0;
CREN = 1;
}

while(!RCIF);  // Wait for transmission to receive

return RCREG;
}

void SendStringSerially(const unsigned char* st)
{
while(*st)
SendByteSerially(*st++);
}







// Main Function
void main(void)
{
InitUART(); // Intialize UART
   
    SendStringSerially("EMBEDDED_LAB  WWW.SUMMITBHARDWAJ.BLOGSPOT.IN"); // Send string on UART

GIE  = 1;   // Enable global interrupts
    PEIE = 1;   // Enable Peripheral Interrupts

while(1)
{
// Do nothing, as Received character is echoed back in the ISR
// If you decide to disable interrupts, then you can
// echo back characters by uncommenting the line below
// SendByteSerially(ReceiveByteSerially());  //Echo Back
}
}


No comments:

Post a Comment