编程完成一个串口的收发数据程序。要求,单片机与PC机进行串口通 信,PC机发送字符给单片机,单片机统计收到的’A’宇符的个数,在数码管上显示个数。当收到10个’A'时发送宇符串TestOK。‘:当收到20个 ‘A°时发送字符串“Uart oK !‘。通信速率为4800bps,单片机外接晶振频 率力 11.0592WHz。
时间: 2023-12-03 22:46:18 浏览: 41
这是一个基于8051单片机的串口收发数据程序,使用Keil C51进行编译:
```
#include <reg52.h>
#define FOSC 11059200L
#define BAUD 4800
#define TH1_VALUE (256 - FOSC / 12 / BAUD)
sbit LED = P1^0;
sbit D0 = P2^0;
sbit D1 = P2^1;
sbit D2 = P2^2;
sbit D3 = P2^3;
unsigned char count = 0;
unsigned char rx_data = 0;
unsigned char tx_data[8] = "TestOK\r\n";
unsigned char tx_data2[11] = "Uart oK !\r\n";
void delay(unsigned int time)
{
unsigned int i, j;
for(i = 0; i < time; i++)
for(j = 0; j < 125; j++);
}
void init_serial()
{
SCON = 0x50; // 8-bit variable baud rate; UART mode enabled
TMOD &= 0x0F; // Clear the 4-bit field for Timer 1
TMOD |= 0x20; // Set Timer 1 in Mode 2
TH1 = TH1_VALUE; // Set the baud rate
TR1 = 1; // Start Timer 1
TI = 1; // Indicate TX ready
}
void serial_tx(unsigned char data)
{
SBUF = data; // Load data into SBUF
while(TI == 0); // Wait until TX complete
TI = 0; // Clear the flag
}
void serial_tx_string(unsigned char *str)
{
while(*str)
serial_tx(*str++);
}
void main()
{
LED = 0;
init_serial();
while(1)
{
if(RI == 1) // Check if data is received
{
rx_data = SBUF; // Read the received data
RI = 0; // Clear the flag
if(rx_data == 'A')
{
count++;
if(count == 10)
{
serial_tx_string(tx_data);
count = 0;
}
else if(count == 20)
{
serial_tx_string(tx_data2);
count = 0;
}
D0 = count % 2;
D1 = (count / 2) % 2;
D2 = (count / 4) % 2;
D3 = (count / 8) % 2;
}
}
}
}
```
在程序中,我们首先定义了晶振频率和通信速率的常量,以及需要使用的IO口。然后定义了计数器count和接收到的数据rx_data,以及需要发送的字符串tx_data和tx_data2。接下来是一些辅助函数,如延时函数和串口初始化函数。在主函数中,我们先初始化串口,然后进入一个无限循环,不断检测是否有数据接收到。如果接收到的数据是字符'A',就增加计数器count,并根据要求进行处理,同时在数码管上显示当前的计数值。如果接收到的数据不是字符'A',则不进行任何处理。