#MA PIC Both side serial communication

 


#include<p18f4520.h>

#pragma config OSC=HS

#pragma config PWRT=OFF

#pragma config WDT=OFF

#pragma config DEBUG=OFF, LVP=OFF


void  sendUSART (void);

void tx_data(unsigned char);

unsigned char rx_data(void);


unsigned char serial_data;


unsigned char text[]="\n\rThis is a both side serial communication.";

unsigned int i=0;


void main(void)


{     ADCON1=0x0F;

TXSTA=0X20;

SPBRG=12; //BAUDRATE=4800

RCSTAbits.SPEN = 1;                               // To activate Serial port (TX and RX pins)

        TXSTAbits.TXEN = 1;                               // To enable transmission

        RCSTAbits.CREN = 1;                               // To enable continuous reception

sendUSART ();

while(1)

        {

        serial_data=rx_data();    // Receive data from PC

        tx_data(serial_data+1);        // Transmit the same data back to PC

        }

}


void  sendUSART (void)

{

while(text[i]!='\0')

{

while(PIR1bits.TXIF==0);

TXREG=text[i];

i++;

}

    

}


void tx_data(unsigned char data1)

{

    TXREG=data1;                                     // Store data in Transmit register

    while (PIR1bits.TXIF == 0);                       // Wait until TXIF gets low

}



unsigned char rx_data(void)

{

    while (PIR1bits.RCIF == 0);                     // Wait until RCIF gets low

    return RCREG;                                   // Retrieve data from reception register

}


Comments