51单片机使用串口通信发送和接收数帧数据的代码
时间: 2023-08-29 09:13:31 浏览: 160
下面是基于51单片机的串口通信发送和接收数帧数据的代码:
发送数据的代码:
```c
#include <reg51.h>
#define BAUD_RATE 9600
void UART_Init()
{
TMOD |= 0x20; // Timer1 work on mode 2
TH1 = 256 - (11059200/12/32/BAUD_RATE); // Set the baud rate
TR1 = 1; // Start timer1
SCON = 0x50; // Mode 1, 8-bit data, enable receive
}
void UART_SendByte(unsigned char dat)
{
SBUF = dat;
while(!TI);
TI = 0;
}
void UART_SendData(unsigned char *buf, int len)
{
int i;
for(i=0; i<len; i++)
UART_SendByte(buf[i]);
}
```
接收数据的代码:
```c
#include <reg51.h>
#define BAUD_RATE 9600
unsigned char RX_BUF[32];
unsigned char RX_CNT = 0;
bit RX_FLAG = 0;
void UART_Init()
{
TMOD |= 0x20; // Timer1 work on mode 2
TH1 = 256 - (11059200/12/32/BAUD_RATE); // Set the baud rate
TR1 = 1; // Start timer1
SCON = 0x50; // Mode 1, 8-bit data, enable receive
ES = 1; // Enable serial interrupt
EA = 1; // Enable global interrupt
}
void UART_RxInt() interrupt 4
{
if(RI) // Receive interrupt flag
{
RI = 0;
RX_BUF[RX_CNT++] = SBUF;
if(RX_CNT >= 32)
RX_CNT = 0;
RX_FLAG = 1;
}
}
void UART_RecvData(unsigned char *buf, int len)
{
int i;
while(!RX_FLAG); // Wait for data to be received
for(i=0; i<len; i++)
buf[i] = RX_BUF[i];
RX_CNT = 0;
RX_FLAG = 0;
}
```
在主程序中,需要先初始化串口,然后可以使用UART_SendData和UART_RecvData函数来发送和接收数据。例如,发送一个长度为5的数据帧,可以这样写:
```c
unsigned char data[] = {0x01, 0x02, 0x03, 0x04, 0x05};
UART_Init();
UART_SendData(data, 5);
```
接收一个长度为10的数据帧,可以这样写:
```c
unsigned char buf[10];
UART_Init();
UART_RecvData(buf, 10);
```
阅读全文