本帖最后由 tomli561 于 2019-11-21 16:53 编辑
在进行通信时,第一次主机向丛机发送数据的时候地址只判断一次,但是之后再判断就要进行两次地址判断(有时候是连续两次进行判断,有时候又是判断一次卡主再按一下地址按键就判断完进入待发送数据)
代码如下:
#include <reg52.h>
#define uchar unsigned char
#define uint unsigned int
#define KEY P0
sbit LED1 = P3^3;
sbit LED2 = P3^4;
sbit MCU1 = P2^0;
sbit MCU2 = P2^1;
sbit rs485dir = P3^2;
uchar x,b;
uchar dz[] = {0x00,0x01,0x02,0x03,0x04,0x05,0x06,0x07,0x08};
uchar code tab[] = {0xc0,0xf9,0xa4,0xb0,0x99,0x92,0x82,0xf8,
0x80,0x90,0x88,0x83,0xc6,0xa1,0x86,0x8e};
uchar keyscan();
void delay(uint t);
void init();
uchar keyscan() //键盘处理函数
{
uchar a,c;
KEY=0x0f; //键盘口置00001111
if(KEY!=0x0f) //查询键口值是否变化
{
delay(20); //去抖
if(KEY!=0x0f) // 有键按下
{
a=KEY; //键值放在寄存器a中
}
KEY=0xf0; //将键盘口置11110000
c=KEY; //将第二次取得值放入寄存器c中
a=a|c; //将两个数据融合
switch(a) //对比数据值
{
case 0xee : b=0;break;
case 0xde : b=1;break;
case 0xbe : b=2;break;
case 0x7e : b=3;break;
case 0xed : b=4;break;
case 0xdd : b=5;break;
case 0xbd : b=6;break;
case 0x7d : b=7;break;
case 0xeb : b=8;break;
case 0xdb : b=9;break;
case 0xbb : b=10;break;
case 0x7b : b=11;break;
case 0xe7 : b=12;break;
case 0xd7 : b=13;break;
case 0xb7 : b=14;break;
case 0x77 : b=15;break;
default:break; //键值错误处理
}
}
return(b); //将b作为返回值
}
void delay(uint t)
{
uchar i,j;
for(i=0;i<120;i++)
for(j=0;j<t;j++);
}
void init()
{
TMOD = 0x20;
TH1 = 0xfd;
TL1 = 0xfd;
SCON = 0xd0;
PCON = 0x00;
TR1 = 1;
rs485dir = 1;
EA = 1;
// ES = 1;
MCU1 = 1;
MCU2 = 1;
KEY = 0x0f;
}
void main()
{
uchar ADDR;
uchar temp;
init();
while(1)
{
P1 = 0XBF;
temp++;
while(temp!=ADDR)
{
LED1 = 1;
LED2 = 1;
TI = 0;
TB8 = 1;
rs485dir = 1;
delay(20);
while(!(MCU1^MCU2));
if(MCU1==0)
{
delay(50);
if(MCU1==1)
ADDR = dz[0];
}
if(MCU2==0)
{
delay(50);
if(MCU1==1)
ADDR = dz[1];
}
SBUF = ADDR;
while(!TI);
TI = 0;
rs485dir = 0;
delay(20);
LED1 = 0;
LED2 = 1;
P1 = tab[ADDR];
delay(20);
while(!RI);
temp = SBUF;
RI = 0;
delay(20);
}
P1 = 0x40;
rs485dir = 1;
TB8 = 0;
delay(10);
while(KEY==0x0f);
keyscan();
SBUF = tab;
while(!TI);
TI = 0;
P1 = 0xa4;
LED1 = 0;
LED2 = 1;
}
}
|