#include <reg52.h>
/* UART Buffer Defines */
#define UART_RX_BUFFER_SIZE 16 /* 1,2,4,8,16,32,64,128 or 256 bytes */
#define UART_RX_BUFFER_MASK ( UART_RX_BUFFER_SIZE - 1 )
#define UART_TX_BUFFER_SIZE 16 /* 1,2,4,8,16,32,64,128 or 256 bytes */
#define UART_TX_BUFFER_MASK ( UART_TX_BUFFER_SIZE - 1 )
/* Static Variables */
staticdata unsigned char UART_RxBuf[UART_RX_BUFFER_SIZE];
static data volatile unsigned char UART_RxHead;
static data volatile unsigned char UART_RxTail;
staticdata unsigned char UART_TxBuf[UART_TX_BUFFER_SIZE];
static data volatile unsigned char UART_TxHead;
static data volatile unsigned char UART_TxTail;
bit fSeri0_Send_Ok;
/* initialize UART */
//t2 做波特率发生器 9600bps at 11.0592 MHz
void InitUART()
{
unsigned char x;
T2CON = 0x30;//t2 做波特率发生器
TH2 = 0xFF;
TL2 = 0xdc;
RCAP2H = 0xFF;
RCAP2L = 0xdc;
SCON = 0x50;/* SM0 SM1 SM2 REN TB8 RB8 TI RI:9 bit */
PCON = 0x00;/* baut rate, 80h:double; 00h: normal*/
ES = 1;/* 串口中断允许1-enable*/
PS = 0;/* 串口中断优先级 1-高,0-低*/
TR2 = 1;/* Start T2 as baut rate generator*/
x = 0; /* flush receive buffer */
UART_RxTail = x;
UART_RxHead = x;
UART_TxTail = x;
UART_TxHead = x;
}
/* interrupt handlers */
void UART_interrupt( void ) interrupt 4
{
if (TI)
{ // 是否是发送中断
unsigned char tmptail;
TI=0;
if (UART_TxTail==UART_TxHead)
{
fSeri0_Send_Ok=0;/*已发送完毕*/
}
else
{
tmptail = ( UART_TxTail + 1 ) &
UART_TX_BUFFER_MASK;
UART_TxTail = tmptail; /* store new index */
SBUF = UART_TxBuf[tmptail]; /* start
transmition */
}
}
if (RI)
{
unsigned char revdata;
unsigned char tmphead;
RI=0;
revdata = SBUF;
tmphead = ( UART_RxHead + 1 ) & UART_RX_BUFFER_MASK;
UART_RxHead = tmphead; /* store new index */
UART_RxBuf[tmphead] = revdata; /* store received data in
buffer */
}
}
unsigned char ReceiveByte( void )
{
unsigned char tmptail;
while ( UART_RxHead == UART_RxTail ) /* wait for incomming data */
;
tmptail = ( UART_RxTail + 1 ) & UART_RX_BUFFER_MASK;/* calculate
buffer index */
UART_RxTail = tmptail; /* store new index */
return UART_RxBuf[tmptail]; /* return data */
}
void TransmitByte( unsigned char senddata )
{
unsigned char tmphead;
tmphead = ( UART_TxHead + 1 ) & UART_TX_BUFFER_MASK;
UART_TxBuf[tmphead] = senddata; /* store data in buffer */
UART_TxHead = tmphead; /* store new index */
if(fSeri0_Send_Ok==0)
{
fSeri0_Send_Ok=1;
TI=1;
}
}
unsigned char DataInReceiveBuffer( void )
{
return ( UART_RxHead != UART_RxTail );
}
void main(void)
{
InitUART() ;
EA=1;
while(1)
{
if (DataInReceiveBuffer())
{
TransmitByte(ReceiveByte());
}
}
}