两个51单片机分别连接一个四位共阳7段数码管(数码管段选引脚连接P0口、位选引脚连接P2口),两个单片机进行串口通信,要求单片机1的共阳数码管初始显示2313,单片机2的共阳数码管初始显示2305,按下按钮两个单片机互相发送并接受数据并显示在共阳数码管上(按下按钮后单片机1显示2305、单片机2显示2313),请写出符合上述要求的代码
时间: 2023-07-03 16:18:34 浏览: 124
单片机1代码:
```c
#include <reg51.h>
typedef unsigned char uint8_t;
typedef unsigned int uint16_t;
#define FOSC 11059200L
#define BAUD 9600
sbit LSA = P0 ^ 2;
sbit LSB = P0 ^ 3;
sbit LSC = P0 ^ 4;
sbit K1 = P3 ^ 2;
uint8_t code table[] = {0xc0, 0xf9, 0xa4, 0xb0, 0x99, 0x92, 0x82, 0xf8, 0x80, 0x90};
uint8_t uart_receive() {
while (!RI);
RI = 0;
return SBUF;
}
void uart_send(uint8_t dat) {
SBUF = dat;
while (!TI);
TI = 0;
}
void delay(uint16_t t) {
while (t--);
}
void display(uint16_t num) {
uint8_t i, j;
uint8_t dat[4];
for (i = 0; i < 4; i++) {
dat[i] = num % 10;
num /= 10;
}
for (i = 0; i < 4; i++) {
for (j = 0; j < 8; j++) {
if (i == 0) LSA = 1;
else LSA = 0;
if (i == 1) LSB = 1;
else LSB = 0;
if (i == 2) LSC = 1;
else LSC = 0;
P2 = table[dat[i]];
delay(100);
P2 = 0x00;
}
}
}
void main() {
uint16_t num = 2313;
uint8_t receive_data;
TMOD = 0x20;
TH1 = TL1 = FOSC / 12 / 32 / BAUD - 1;
TR1 = 1;
SM0 = 0;
SM1 = 1;
REN = 1;
while (1) {
display(num);
if (K1 == 0) {
uart_send(num / 1000);
uart_send(num % 1000 / 100);
uart_send(num % 100 / 10);
uart_send(num % 10);
while (K1 == 0);
}
receive_data = uart_receive();
if (receive_data != 0xff) {
num = receive_data * 1000;
receive_data = uart_receive();
num += receive_data * 100;
receive_data = uart_receive();
num += receive_data * 10;
receive_data = uart_receive();
num += receive_data;
}
}
}
```
单片机2代码:
```c
#include <reg51.h>
typedef unsigned char uint8_t;
typedef unsigned int uint16_t;
#define FOSC 11059200L
#define BAUD 9600
sbit LSA = P0 ^ 2;
sbit LSB = P0 ^ 3;
sbit LSC = P0 ^ 4;
sbit K1 = P3 ^ 2;
uint8_t code table[] = {0xc0, 0xf9, 0xa4, 0xb0, 0x99, 0x92, 0x82, 0xf8, 0x80, 0x90};
uint8_t uart_receive() {
while (!RI);
RI = 0;
return SBUF;
}
void uart_send(uint8_t dat) {
SBUF = dat;
while (!TI);
TI = 0;
}
void delay(uint16_t t) {
while (t--);
}
void display(uint16_t num) {
uint8_t i, j;
uint8_t dat[4];
for (i = 0; i < 4; i++) {
dat[i] = num % 10;
num /= 10;
}
for (i = 0; i < 4; i++) {
for (j = 0; j < 8; j++) {
if (i == 0) LSA = 1;
else LSA = 0;
if (i == 1) LSB = 1;
else LSB = 0;
if (i == 2) LSC = 1;
else LSC = 0;
P2 = table[dat[i]];
delay(100);
P2 = 0x00;
}
}
}
void main() {
uint16_t num = 2305;
uint8_t receive_data;
TMOD = 0x20;
TH1 = TL1 = FOSC / 12 / 32 / BAUD - 1;
TR1 = 1;
SM0 = 0;
SM1 = 1;
REN = 1;
while (1) {
display(num);
if (K1 == 0) {
uart_send(num / 1000);
uart_send(num % 1000 / 100);
uart_send(num % 100 / 10);
uart_send(num % 10);
while (K1 == 0);
}
receive_data = uart_receive();
if (receive_data != 0xff) {
num = receive_data * 1000;
receive_data = uart_receive();
num += receive_data * 100;
receive_data = uart_receive();
num += receive_data * 10;
receive_data = uart_receive();
num += receive_data;
}
}
}
```
阅读全文