采用c8051f340单片机,用r485实现
指令随意
下位机 接收/回复
#include <c8051f340.h>
#define uchar unsigned char
#define uint unsigned int
/***********端口初始化函数+******************/
sbit Contrl = P0 ^ 1; //p0.1
char txt[100];
uint l = 0;
uint count = 0;
uint ll = 0;
char tmp;
void PORT_Init(void) {
XBR0 = 0x01;//端口I/O交叉开关寄存器0
XBR1 = 0x40;//端口I/O交叉开关寄存器1,交叉开关使能
P0MDOUT = 0x10;//P0.4为推挽输出,其他的为漏极开路输出
P0MDOUT |= 0x02;//P0.1也为推挽输出
}
void UART0_Init(void) {
SCON0 |= 0x10;
CKCON = 0x01;
TH1 = 0x64;//波特率为9600
TL1 = TH1;
TMOD = 0x20;
TR1 = 1;//P235,定时器1运行控制,定时器1允许
TI0 = 1;//P235,中断1类型选择,INT1为边沿触发
}
void main() {
char g;
PCA0MD &= ~0x40;//关闭看门狗
OSCICN |= 0x03;//P126
PORT_Init();//端口初始化
UART0_Init();//UART0初始化
Contrl = 0;//485接收状态
TI0 = 0;
while (1) {
if (l>0)
{
count++;
if (count>1000)
{
Contrl = 1;//485发送状态
ll = 0;
while (ll < l)
{
tmp= txt[ll];
SBUF0 = tmp;
while (TI0 == 0);//发送
TI0 = 0;
ll++;
}
l = 0;
Contrl = 0;//485接收状态
}
}
if (RI0==0)
{
continue;
}
tmp= SBUF0;
txt[l]= tmp;
l++;
RI0 = 0;
count = 0;
}
}
请各位帮忙