51单片机串口通信接受和发送数据代码
时间: 2024-01-30 13:03:20 浏览: 130
以下是51单片机串口通信接受和发送数据的代码:
//头文件
#include <reg51.h>
//定义波特率
#define BAUDRATE 9600
//定义串口接收缓冲区大小
#define RX_BUFFER_SIZE 64
//定义串口发送缓冲区大小
#define TX_BUFFER_SIZE 64
//定义串口接收缓冲区
unsigned char rx_buffer[RX_BUFFER_SIZE];
//定义串口接收缓冲区头指针
unsigned char rx_buffer_head = 0;
//定义串口接收缓冲区尾指针
unsigned char rx_buffer_tail = 0;
//定义串口发送缓冲区
unsigned char tx_buffer[TX_BUFFER_SIZE];
//定义串口发送缓冲区头指针
unsigned char tx_buffer_head = 0;
//定义串口发送缓冲区尾指针
unsigned char tx_buffer_tail = 0;
//串口初始化函数
void UART_Init(void)
{
//设置波特率
TMOD &= 0xF0;
TL1 = TH1 = -(unsigned char)(FOSC/12/BAUDRATE);
TR1 = 1;
//设置数据位,停止位和校验位
SCON = 0x50;
//使能全局中断
EA = 1;
//使能串口中断
ES = 1;
}
//串口发送函数
void UART_Send(unsigned char ch)
{
//如果发送缓冲区已满,则等待
while((tx_buffer_head + 1) % TX_BUFFER_SIZE == tx_buffer_tail);
//将数据存入发送缓冲区
tx_buffer[tx_buffer_head] = ch;
tx_buffer_head = (tx_buffer_head + 1) % TX_BUFFER_SIZE;
//启动发送
TI = 1;
}
//串口接收函数
unsigned char UART_Receive(void)
{
//如果接收缓冲区为空,则等待
while(rx_buffer_head == rx_buffer_tail);
//从接收缓冲区取出数据
unsigned char ch = rx_buffer[rx_buffer_tail];
rx_buffer_tail = (rx_buffer_tail + 1) % RX_BUFFER_SIZE;
return ch;
}
//串口中断服务函数
void UART_ISR(void) interrupt 4
{
//接收中断
if(RI)
{
//清除接收中断标志
RI = 0;
//如果接收缓冲区已满,则忽略数据
if((rx_buffer_head + 1) % RX_BUFFER_SIZE == rx_buffer_tail)
{
return;
}
//将数据存入接收缓冲区
rx_buffer[rx_buffer_head] = SBUF;
rx_buffer_head = (rx_buffer_head + 1) % RX_BUFFER_SIZE;
}
//发送中断
if(TI)
{
//清除发送中断标志
TI = 0;
//如果发送缓冲区为空,则禁止发送中断
if(tx_buffer_head == tx_buffer_tail)
{
return;
}
//从发送缓冲区取出数据并发送
SBUF = tx_buffer[tx_buffer_tail];
tx_buffer_tail = (tx_buffer_tail + 1) % TX_BUFFER_SIZE;
}
}
//主函数
void main(void)
{
//串口初始化
UART_Init();
while(1)
{
//从串口接收数据
unsigned char ch = UART_Receive();
//将接收到的数据原样发送回去
UART_Send(ch);
}
}
阅读全文