Hii Stahiiresh,
1. First off all what compiler you are using?
If you are using KEIL or SDCC you can use this code
2. For receiving data in PC there is 2 methode :
1. Polling Methode ( it means that you are waiting until data is recived and micro can't do anything else)
2. Interrupt Mode ( it means micro can do anything, but if the PC sending data the program stop and give the serive to the Intterupt Serial Vector for handling communication with pc)
From your source code : I think you are using polling methode.
Step for Programming UART :
1. Register Use for UART (SBUF 0x99 , PCON 0x87, SCON 0x98)
2. Decide Timer for Clock
3. Decide Mode :
Mode 0 ==> Syncrohnous
Mode 1 ==> Uart 8 Bit Baud Rate Flexible
Mode 2 ==> Uart 9 Bit Baud Rate Fixed
Mode 3 ==> Uart 9 Bit Baud Rate Flexible ( Multi Processor Communication Master Slave)
Step For Counting Baudrate for Register :
Baudrate = (2^ smod/32) * (Frequency Osilator/(12*(256-TH1)
example :
AT89C51 using Timer 1 using SMOD 1 Baudrate 9600 Frequency Osilator = 11.0592 MHz
9600 = (2^1/32) *(11059200 /(12*(256-TH1))
[256-TH1] = (2^1/32*11059200/9600)
TH1 = 256 - 6 = 250 (Decimal) / 0xFA (Heksa)
The Final Sample Source Code : ( I Use Mide Compiler. It's Free Compiler Using SDCC check this site
http://www.opcube.com/home.html) :
Code:
//==============
// For Polling Methode
//==============
#include <8051.h>
//==============================================
// Serial Inisialisation using 9600 baud rate 8 data bits no parity 1 stop bit
//==============================================
void init_serial(unsigned char baud)
{
TMOD = 0x20; //using timer 1 mode auto reload
PCON = 0;
SM0 = 0;
SM1 = 1; // mode 1 (sm0 = 0 sm1 = 0 ==> mode 0 , sm0 = 1 sm1 = 0 ==> / mode 2)
REN = 1;
TH1 = baud;
TL1 = baud;
TR1 = 1;
}
//====================
// For Send one character to PC
//====================
void send_char(unsigned char datasent)
{
SBUF = datasent;
while(!TI)
{;}
TI = 0;
}
//=====================
// For send some characters to PC
//=====================
void send_text(unsigned char *text)
{
char i = 0;
while (text[i]!=0)
{
send_char(text[i]);
i++;
}
}
//=====================
// For Receive data from PC
//=====================
char get_data_from_pc()
{
while(!RI)
{;}
RI=0;
return SBUF;
}
//===================
// Main Function
//===================
void main(void)
{
unsigned char datapc;
init_serial(0xfa);
while(1)
{
datapc=get_data_from_pc();
send_char(datapc);
}
}