標籤:
第一種方法:在中斷中處理
typedef unsigned char UINT8;volatile UINT8 u8Uart_Data;void InitialUART0_Timer1(){ SCON = 0x50; //2015-05-04 TMOD = 0x20; TH1 = 0XFD; // 9600BPS 2015-05-04 wangrong TL1 = 0XFD; TR1 = 1; // start timer0 ES = 1; // Enable serial interrupt EA = 1; // Enable global interrupt}//-----------------------------------------------------------------------------------------------------------void main (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; } }}//-----------------------------------------------------------------------------------------------------------void UART_ISR(void) interrupt 4{ if (RI) { // If reception occur RI = 0; // Clear reception flag for next reception u8Uart_Data = 0; u8Uart_Data = SBUF; // Read receive data recv_data = 1; //SBUF = u8Uart_Data; // Send back same data on UART } if (TI) // If emission occur { // Clear emission flag for next emission TI = 0; }}//-----------------------------------------------------------------------------------------------------------
第二種方法:不在中斷中處理
//-----------------------------------------------------------------------------------------------------------// Use timer1 as baud rate generatorvoid InitialUART0_Timer1(){ SCON = 0x50; //2015-05-04 TMOD = 0x20;#if 0#ifdef FOSC_110592 TH1 = 256 - (28800/u32Baudrate); /* 11.059M/384=28800 */#endif#ifdef FOSC_184320 TH1 = 256 - (48000/u32Baudrate); /* 18.4320M/384=48000 */#endif#ifdef FOSC_221184 TH1 = 256 - (57600/u32Baudrate); /* 22.1184M/384=57600 */#endif#ifdef FOSC_331776 TH1 = 256 - (86400/u32Baudrate); /* 33.1776M/384=86400 */#endif#ifdef FOSC_368640 TH1 = 256 - (96000/u32Baudrate); /* 36.8640M/384=96000 */#endif#endif /* #if 0 */ TH1 = 0XFD; // 9600BPS 2015-05-04 wangrong TL1 = 0XFD; TR1 = 1; // start timer0 ES = 1; // Enable serial interrupt EA = 1; // Enable global interrupt}//-----------------------------------------------------------------------------------------------------------UINT8 Receive_Data_From_PC(void){ UINT8 c; while (!RI); c = SBUF; RI = 0; return (c);}//-----------------------------------------------------------------------------------------------------------void Send_Data_To_PC (UINT8 c){ while (!TI); TI = 0; SBUF = c;}//-----------------------------------------------------------------------------------------------------------//-----------------------------------------------------------------------------------------------------------void main (void){ //-------------------------------------------------------------------------------- InitialUART0_Timer1(); // 9600 Baud Rate @ 11.0592MHz //--------------------------------------------------------------------------------- while(1) { Receive_Data_From_PC(); Send_Data_To_PC(Receive_Data_From_PC()); }}
51單片機串口接收和發送資料