#include "C8051F020.h"
#include "stdlib.h"
#define INT8U     unsigned char
#define BIT(x)    (0x01 << x)
#define BIT0      0x01
#define BIT1      0x02
#define BIT2      0x04
#define BIT3      0x08
#define BIT4      0x10
#define BIT5      0x20
#define BIT6      0x40
#define BIT7      0x80


void Init_UART0 ()
{
	XBR2    = 0x40;
	XBR0 |= BIT2; //UART0连接到P0.0 P0.1引脚
	P0MDOUT |= BIT0; 

	IE |= BIT4;	//允许UART0中断
	EA = 1;

	SCON0 &= ~(BIT7 + BIT5 + BIT3 + BIT2 + BIT1 + BIT0);
	SCON0 |= BIT6 + BIT4;	 //串口工作方式1


	PCON &= ~(BIT7 + BIT6); //禁止波特率加倍  SSTAT0 = 0

	CKCON &= ~BIT4; // 定时器T1时钟为系统时钟12分频

	TMOD &= ~(BIT7 + BIT6 + BIT4);
	TMOD |= BIT5;

	TH1 = TL1 = 253;
	TR1 = 1;
}


void Send_UART0_Data (INT8U dat)
{
	ES0 = 0;
	TI0 = 0;
	SBUF0 = dat;
	while (!TI0);
	TI0 = 0;
	ES0= 1;
}

void Send_Str_UART0 (char * str, INT8U length)
{
	INT8U i;
	if (str == NULL)
	{
		return ;
	}
	for (i = 0; i < length; i ++) 
	{
		Send_UART0_Data (str[i]);
	}
}
   

void Receive_UART0_Data (INT8U dat)
{
	Send_UART0_Data (dat);		
}

 
 void UART0_ISR(void) interrupt 4
{
	if (RI0 == 1)
	{
		RI0 = 0;
		Receive_UART0_Data (SBUF0);
	}
}	 

void main (void)
{
    unsigned int i;

	WDTCN = 0xde;                       // Disable watchdog timer
	WDTCN = 0xad;

		
  	// OSCICN |= 0x03;                     // Configure internal oscillator	    
	OSCICN |= 0x80;                     // Enable the missing clock detector
	/*使用外部晶振*/
	OSCXCN = 0x67;                      // Enable external crystal osc.
	for (i=0; i < 256; i++);            // Wait at least 1ms
	while (!(OSCXCN & 0x80));           // Wait for crystal osc to settle
	OSCICN |= 0x08;                  	// Select external clock source
	OSCICN &= ~0x04;

	Init_UART0 ();

	while(1)
	{ 
	 	Send_Str_UART0 ("AB", 2);
	   	for (i = 0; i < 60000; i ++); 
  	}  
}