您的位置 首页 硬件

51单片机完成串口接纳和发送数据的两种办法解析

51单片机实现串口接收和发送数据的两种方法解析-第一种方法:在中断中处理

typedef unsigned char UINT8;

volatile UINT8 u8Uart_Data;

void InitialUART0_Timer1()

{

SCON = 0x50; //2015-05-04

TMOD = 0x20;

TH1 = 0XFD; // 9600BPS 2015-05-04

TL1 = 0XFD;

TR1 = 1; // start timer0

ES = 1; // Enable serial interrupt

EA = 1; // Enable global interrupt

榜首种方法:在中止中处理

typedef unsigned char UINT8;

volaTIle UINT8 u8Uart_Data;

void IniTIalUART0_TImer1()

{

SCON = 0x50; //2015-05-04

TMOD = 0x20;

TH1 = 0XFD; // 9600BPS 2015-05-04

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 generator

void 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

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());

}

}

声明:本文内容来自网络转载或用户投稿,文章版权归原作者和原出处所有。文中观点,不代表本站立场。若有侵权请联系本站删除(kf@86ic.com)https://www.86ic.net/qianrushi/yingjian/346219.html

为您推荐

联系我们

联系我们

在线咨询: QQ交谈

邮箱: kf@86ic.com

关注微信
微信扫一扫关注我们

微信扫一扫关注我们

返回顶部