First method: Handling in interrupts
typedef unsignedCharUINT8;volatileUINT8 U8uart_data;voidInitialuart0_timer1 () {SCON=0x50;//2015-05-04Tmod =0x20; TH1=0XFD;//9600BPS 2015-05-04 WangrongTL1 =0XFD; TR1=1;//Start Timer0ES =1;//Enable serial InterruptEA =1;//Enable Global Interrupt}//----------------------------------------------------------------------------------------------------------- voidMain (void){ //--------------------------------------------------------------------------------Initialuart0_timer1 ();//9600 Baud rate @ 11.0592MHz while(1) { //receive_data_from_pc (); //send_data_to_pc (RECEIVE_DATA_FROM_PC ()); while(recv_data) {Recv_data=0; TI=0; Sbuf=U8uart_data; } }}//----------------------------------------------------------------------------------------------------------- voidUART_ISR (void) Interrupt4{ if(RI) {//If reception occurRI =0;//Clear Reception flag for next receptionU8uart_data =0; U8uart_data= Sbuf;//Read receive DataRecv_data =1; //sbuf = U8uart_data; //Send back same data on UART } if(TI)//If emission occur{//Clear emission flag for next emissionTI =0; }}//-----------------------------------------------------------------------------------------------------------
Second method: Do not process in interrupts
//----------------------------------------------------------------------------------------------------------- //Use timer1 as baud rate generatorvoidInitialuart0_timer1 () {SCON=0x50;//2015-05-04Tmod =0x20;#if0#ifdef fosc_110592 TH1= the- (28800/u32baudrate);/*11.059m/384=28800*/#endif#ifdef fosc_184320 TH1= the- (48000/u32baudrate);/*18.4320m/384=48000*/#endif#ifdef fosc_221184 TH1= the- (57600/u32baudrate);/*22.1184m/384=57600*/#endif#ifdef fosc_331776 TH1= the- (86400/u32baudrate);/*33.1776m/384=86400*/#endif#ifdef fosc_368640 TH1= the- (96000/u32baudrate);/*36.8640m/384=96000*/#endif#endif/* #if 0 */TH1=0XFD;//9600BPS 2015-05-04 WangrongTL1 =0XFD; TR1=1;//Start Timer0ES =1;//Enable serial InterruptEA =1;//Enable Global Interrupt}//----------------------------------------------------------------------------------------------------------- UINT8 RECEIVE_DATA_FROM_PC (void) {UINT8 C; while(!RI); C=Sbuf; RI=0; return(c);}//----------------------------------------------------------------------------------------------------------- voidsend_data_to_pc (UINT8 c) { while(!TI); TI=0; Sbuf=C;}//----------------------------------------------------------------------------------------------------------- //----------------------------------------------------------------------------------------------------------- voidMain (void){ //--------------------------------------------------------------------------------Initialuart0_timer1 (); //9600 Baud rate @ 11.0592MHz//--------------------------------------------------------------------------------- while(1) {receive_data_from_pc (); SEND_DATA_TO_PC (RECEIVE_DATA_FROM_PC ()); }}
51 single-chip computer serial port to receive and transmit data