用C51编程完成⼀个串口的收发数据程序。要求,单片机与 PC 机进行串口通 信,PC 机发送字符给单片机,单片机统计收到的'A'字符的个数,在数码 管上显示个数。当收到 10 个'A'时发送字 符串 Test OK。';当收到 20 个 'A'时发送字符串'Uart OK !'。通信速率为 4800bps,单片机外接晶振频 率为 11.0592MHz。 扩展要求: 在上述程序的基础上,将对单个字符的判断增加为对一个字符串的判断。 用单片机统计收到的字符串是否正确,如果收到字符串'Test'时表示正 确,单片机回送字符串'Uart OK !'。
时间: 2024-02-15 15:01:52 浏览: 35
好的,下面是可以参考的C51代码:
```C
#include <reg52.h>
#define FREQ_OSC 11059200UL
#define BAUD_RATE 4800UL
sbit LED = P1^0;
void init_serial() {
SCON = 0x50;
TMOD &= 0x0F;
TMOD |= 0x20;
TH1 = 256 - FREQ_OSC / (12 * 32 * BAUD_RATE);
TL1 = TH1;
TR1 = 1;
}
void send_serial(char c) {
SBUF = c;
while(!TI);
TI = 0;
}
char receive_serial() {
while(!RI);
RI = 0;
return SBUF;
}
void main() {
char c;
int count_A = 0;
char str[5] = {'\0'};
int str_index = 0;
init_serial();
while(1) {
//接收字符
c = receive_serial();
//统计'A'字符的个数
if(c == 'A') {
count_A++;
if(count_A == 10) {
send_serial('T');
send_serial('e');
send_serial('s');
send_serial('t');
send_serial(' ');
send_serial('O');
send_serial('K');
send_serial('\n');
} else if(count_A == 20) {
send_serial('U');
send_serial('a');
send_serial('r');
send_serial('t');
send_serial(' ');
send_serial('O');
send_serial('K');
send_serial('!');
send_serial('\n');
}
} else {
count_A = 0;
}
//判断字符串是否正确
if(c == 'T' || c == 'e' || c == 's' || c == 't') {
str[str_index++] = c;
} else {
str_index = 0;
str[0] = '\0';
}
if(str_index == 4) {
if(strcmp(str, "Test") == 0) {
send_serial('U');
send_serial('a');
send_serial('r');
send_serial('t');
send_serial(' ');
send_serial('O');
send_serial('K');
send_serial('!');
send_serial('\n');
}
str_index = 0;
str[0] = '\0';
}
}
}
```
注意,该代码只是一个示例,需要根据实际情况进行调整和完善。同时,该代码只是串口通信的核心代码,需要在外部加入数码管显示等模块。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)