(系统晶振为11.0952MHz,串口接收采用8位通信,波特率为9600)请编程实现以下功能。 (1)数码管接p1.0到p1.6,到编制串口通信程序,每当接收到超级终端发来的一位数字(假设只能是0~9的数字),请把接收到的数字显示在数码管上。 (2)当P2口上的开关状态有变化时,请把P2口的状态通过串口发送给超级终端。
时间: 2024-02-11 17:06:56 浏览: 86
以下是实现上述功能的代码:
```c
#include <reg52.h>
#define FREQ_OSC 11059200UL // 晶振频率
#define BAUD_RATE 9600 // 波特率
sbit LED = P1^7; // 数码管共阴极接P1.7
sbit SW = P2^0; // P2.0接开关
void initSerial() {
TMOD |= 0x20; // 设置定时器1为模式2(8位自动重载)
TH1 = 256 - FREQ_OSC / 12 / BAUD_RATE; // 设置定时器1初值
TL1 = TH1;
TR1 = 1; // 启动定时器1
SCON = 0x50; // 设置串口为模式1(8位数据,无校验,1位停止位,可变波特率)
}
void sendSerial(char c) {
SBUF = c; // 发送数据
while (!TI); // 等待发送完成
TI = 0; // 清除发送完成标志
}
char receiveSerial() {
while (!RI); // 等待接收完成
RI = 0; // 清除接收完成标志
return SBUF; // 返回接收到的数据
}
void delay(unsigned int t) {
unsigned int i, j;
for (i = 0; i < t; i++)
for (j = 0; j < 200; j++);
}
void displayNumber(char num) {
static unsigned char code[] = {
0x3f, 0x06, 0x5b, 0x4f, 0x66,
0x6d, 0x7d, 0x07, 0x7f, 0x6f
};
LED = 1; // 打开数码管
P1 = code[num % 10]; // 显示个位数
delay(5);
LED = 0; // 关闭数码管
}
void main() {
char num;
initSerial(); // 初始化串口
while (1) {
num = receiveSerial(); // 接收数据
displayNumber(num); // 显示数字
if (SW != 0) // 检测开关状态
sendSerial('1');
else
sendSerial('0');
}
}
```
该程序使用定时器1和串口实现了数字显示和开关状态检测并发送功能。其中,`initSerial`函数初始化了串口,`sendSerial`函数发送数据,`receiveSerial`函数接收数据,`delay`函数实现了短暂的延时,`displayNumber`函数通过数码管显示数字,`main`函数中实现了循环接收数据并根据数据显示数字并发送开关状态的功能。需要注意的是,由于数码管的共阴极接P1.7,因此需要将P1.7设置为输出模式,并在显示数字时将其置为高电平以打开数码管。
阅读全文
相关推荐
![-](https://img-home.csdnimg.cn/images/20241231044833.png)
![-](https://img-home.csdnimg.cn/images/20241231044937.png)
![-](https://img-home.csdnimg.cn/images/20241231044955.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)
![](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)