测试RS485通信电路。
一、硬件电路
1.1、选择RS485通信通道
1.2、RS485电路
二、程序
2.1、main.c
#include "config.h"
void main(void)
{
uint i=0;
Init_led();
Init_key();
Init_uart(32, 9600);
Init_rs485();
uart_chl(0); //RS485
while(1)
{
}
}
2.2、uart.c
#include "config.h"
bit UartSendFlag = 0; //·¢ËÍÖжϱê־λ
bit UartReceiveFlag = 0; //½ÓÊÕÖжϱê־λ
void uart_chl(uchar ul)
{
switch (ul)
{
case 0: //rs485
UART_CHA=0;
UART_CHB=0;
break;
case 1: //usb-ttl
UART_CHA=1;
UART_CHB=0;
break;
default:
break;
}
}
void Init_uart(uint Freq, unsigned long int baud)
{
P2CON &= ~0x03;
P2PH |= 0x03;
P5CON &= ~0x14 ; //0001 0100
P5CON |= 0x14 ;
P5PH |= 0x14;
SCON |= 0X50;
TMCON |= 0X02;
TH1 = (Freq*1000000/baud)>>8;
TL1 = Freq*1000000/baud;
TR1 = 0;
ET1 = 0;
EUART = 1;
EA = 1;
}
void uart_send_char(uchar ch)
{
SBUF=ch;
while(TI==0);
TI=0;
}
void uart_send_string(uchar *str)
{
while(*str )
{
uart_send_char(*str ++);
}
}
////uartint
void UartInt(void) interrupt 4
{
// if(TI)
// {
// TI = 0;
// UartSendFlag = 1;
// }
if(RI)
{
RI = 0;
//UartReceiveFlag = 1;
rs485_send_char(SBUF);
}
}
void Init_rs485(void)
{
P5CON &= ~0x02 ;//0000 0010
P5CON |= 0x02 ;
RS485_RX();
}
void rs485_send_char(uchar dat)
{
RS485_TX();
uart_send_char(dat);
RS485_RX();
}
2.3、uart.h
#ifndef __UART_H__
#define __UART_H__
sbit UART_CHA = P5^2;
sbit UART_CHB = P5^4;
sbit RS485_CH = P5^1; //1--RX 0--TX
#define RS485_RX() RS485_CH=1
#define RS485_TX() RS485_CH=0
void Init_uart(uint Freq, unsigned long int baud);
void uart_chl(uchar ul);
void uart_send_char(uchar ch);
void uart_send_string(uchar *str);
void Init_rs485(void);
void rs485_send_char(uchar dat);
#endif
三、运行
3.1、连接图
3.2、RS485收到一个字节,再发送出去。
|