两个51单片机基于rs485通讯并显示经过实测的程序
时间: 2024-05-16 22:18:08 浏览: 132
以下是两个51单片机基于RS485通讯并显示经过实测的程序。
主机程序:
```c
#include <REGX52.H>
#include <stdio.h>
sbit RS485_RW = P1^0;
sbit RS485_REN = P1^1;
sbit LED = P2^0;
void delay(unsigned int t)
{
unsigned int i, j;
for(i=0; i<t; i++)
for(j=0; j<125; j++);
}
void init_uart()
{
SCON = 0x50;
TMOD = 0x20;
TH1 = 0xFD;
TL1 = 0xFD;
TR1 = 1;
}
void init_rs485()
{
RS485_RW = 0;
RS485_REN = 0;
}
void send_data(unsigned char c)
{
SBUF = c;
while(TI == 0);
TI = 0;
}
void send_string(unsigned char *str)
{
while(*str != '\0')
{
send_data(*str);
str++;
}
}
void main()
{
unsigned char i;
unsigned char buf[10];
init_uart();
init_rs485();
while(1)
{
for(i=0; i<10; i++)
{
buf[i] = i + '0';
}
RS485_RW = 1;
RS485_REN = 1;
send_string(buf);
RS485_RW = 0;
RS485_REN = 0;
LED = ~LED;
delay(1000);
}
}
```
从机程序:
```c
#include <REGX52.H>
#include <stdio.h>
sbit RS485_RW = P1^0;
sbit RS485_REN = P1^1;
sbit LED = P2^0;
void delay(unsigned int t)
{
unsigned int i, j;
for(i=0; i<t; i++)
for(j=0; j<125; j++);
}
void init_uart()
{
SCON = 0x50;
TMOD = 0x20;
TH1 = 0xFD;
TL1 = 0xFD;
TR1 = 1;
}
void init_rs485()
{
RS485_RW = 0;
RS485_REN = 0;
}
void send_data(unsigned char c)
{
SBUF = c;
while(TI == 0);
TI = 0;
}
void send_string(unsigned char *str)
{
while(*str != '\0')
{
send_data(*str);
str++;
}
}
void main()
{
unsigned char c;
init_uart();
init_rs485();
while(1)
{
RS485_RW = 0;
RS485_REN = 0;
while(RI == 0);
c = SBUF;
RI = 0;
RS485_RW = 1;
RS485_REN = 1;
send_data(c);
LED = ~LED;
}
}
```
注意事项:
1. 两个单片机需要使用相同的波特率。
2. 两个单片机需要连接一根RS485通讯线,其中A线连接到A线,B线连接到B线。
3. 主机发送数据时,需要将RE/DE引脚设置为高电平,接收数据时需要将RE/DE引脚设置为低电平。
4. 从机接收数据时,需要将RE/DE引脚设置为低电平,发送数据时需要将RE/DE引脚设置为高电平。
阅读全文