多机通信系统设计。 功能描述:一台主机,3台从机,从机地址分别为00H、01H、02H。对于主机,能够根据P1口的四位拨码开关的编程状态从3个从机中选择一个,读取P2开关的状态并从串口发送出去;对于从机,只有被选中的从机可以接收主机发送的开关状态,通过P2口的发光二极管显示;的C语言程序
时间: 2024-02-12 19:08:04 浏览: 95
多机通信(从机发送主机接收)
以下是多机通信系统的C语言程序示例,包括主机和从机的程序:
主机程序:
```c
#include <reg52.h>
#include <stdio.h>
#define BAUDRATE 9600
#define ADDR_00 0x00
#define ADDR_01 0x01
#define ADDR_02 0x02
sbit P1_0 = P1^0;
sbit P1_1 = P1^1;
sbit P1_2 = P1^2;
sbit P1_3 = P1^3;
sbit P2_0 = P2^0;
sbit P2_1 = P2^1;
sbit P2_2 = P2^2;
sbit P2_3 = P2^3;
unsigned char address;
unsigned char data;
void init_serial()
{
TMOD |= 0x20;
TH1 = 256 - (11059200/12/32/BAUDRATE);
TL1 = TH1;
TR1 = 1;
SM0 = 0;
SM1 = 1;
REN = 1;
}
void send_data(unsigned char addr, unsigned char data)
{
SBUF = addr;
while(!TI);
TI = 0;
SBUF = data;
while(!TI);
TI = 0;
}
unsigned char read_switch()
{
unsigned char value = 0;
value |= P2_0 << 0;
value |= P2_1 << 1;
value |= P2_2 << 2;
value |= P2_3 << 3;
return value;
}
void main()
{
init_serial();
while(1)
{
if(P1_0 == 0)
address = ADDR_00;
else if(P1_1 == 0)
address = ADDR_01;
else if(P1_2 == 0)
address = ADDR_02;
else
continue;
data = read_switch();
send_data(address, data);
}
}
```
从机程序:
```c
#include <reg52.h>
#include <stdio.h>
#define BAUDRATE 9600
#define ADDR_00 0x00
#define ADDR_01 0x01
#define ADDR_02 0x02
sbit P2_0 = P2^0;
sbit P2_1 = P2^1;
sbit P2_2 = P2^2;
sbit P2_3 = P2^3;
unsigned char address;
unsigned char data;
void init_serial()
{
TMOD |= 0x20;
TH1 = 256 - (11059200/12/32/BAUDRATE);
TL1 = TH1;
TR1 = 1;
SM0 = 0;
SM1 = 1;
REN = 1;
}
void display_data(unsigned char data)
{
P2_0 = data & 0x01;
P2_1 = data & 0x02;
P2_2 = data & 0x04;
P2_3 = data & 0x08;
}
void main()
{
init_serial();
while(1)
{
if(RI)
{
address = SBUF;
while(!TI);
TI = 0;
data = SBUF;
while(!TI);
TI = 0;
if(address == ADDR_00 || address == ADDR_01 || address == ADDR_02)
{
display_data(data);
}
}
}
}
```
以上程序仅供参考,具体实现过程中需要根据具体的单片机和通信协议进行调整。
阅读全文