|
我用一个AT2051作主机,频率为12M,用89C51 作从机,频率为 6M,测试其串口通讯,不知道为什么不能工作,请大家斧正:
主机程序:
#include <AT892051.h>
unsigned char buf[4] ={8, 7, 6, 5};
//unsigned char *p;
unsigned char CheckSum;
initialize()
{
TMOD =0x20;
TH1 =0xE6;
TL1 =0xE6;
PCON =0x00;
TR1 =1;
SCON =0x50;
//EA =1; //开中断
IE = 0X80; //T1 ET1 中断关闭
}
send(unsigned *pt)
{
unsigned char i;
do{
SBUF =0xaa;
while(TI==0);
TI =0;
while(RI==0);
RI =0;
}while(SBUF !=0xbb); // 发送AA 接收BB 作为联络信号
do{
CheckSum =0;
for(i=0;i<4;i++)
{
SBUF =pt;
//CheckSum +=p;
while(TI ==0);
TI =0;
CheckSum +=pt;
}
SBUF =CheckSum;
while(TI==0);
TI =0;
while(RI==0);
RI =0;
}while(SBUF !=0x00); // 返回00表示接收成功,否则表示不成功,继续重发
}
void main()
{
initialize();
send(buf);
}
从机程序:
#include <reg51.h>
unsigned char buf[4];
unsigned char PortN[10] ={0x40, 0xF9, 0XA4, 0XB0, 0X99, 0X92, 0X82, 0XF8, 0X80, 0X98};
//unsigned char *p;
unsigned char CheckSum;
unsigned char Bdisplay;
//unsigned char ThB =8, SeB =7, FiB =6, ZeB =5;
unsigned char ThB, SeB, FiB, ZeB;
unsigned char j =0;
void timer0(void) interrupt 1 using 1 //定时器 0工作在方式 1
{
TH0 =0XFE; //定时时间为1MS
TL0 =0X0C;
Bdisplay =1;
}
initialize() //串口初始化
{
//TMOD =0x20; //T/C1工作在定时方式2
TMOD =0x10;
TH1 =0xE6; //定时器1 设置波特率
TL1 =0xE6;
PCON =0x80;
SCON =0x50;
//IE =0X92; //定时器1 作为波特率发生器应禁止其中断
IE =0X82;
//EA =1;
PS =1; //串口中断优先级
TR1 =1;
}
void receive(unsigned char *pt)
{
do{
while(RI==0);
RI =0;
}while(SBUF !=0xaa);
SBUF =0Xbb;
while(TI ==0);
TI =0;
while(1)
{
unsigned char i;
CheckSum =0;
for(i=0;i<4;i++)
{
while(RI ==0); //接收完成再赋值,发送是先赋值然后等待发送完成
RI =0;
pt =SBUF;
//while(RI ==0);
//RI =0;
CheckSum +=pt;
}
while(RI ==0); //等待校验码接收完成
RI =0;
if(SBUF ==CheckSum)
{
SBUF =0X00; //校验和相同发送 00
while(TI ==0);
TI =0;
break; //如果检验成功,退出发送循环 ???break 语句能否用在此处????
}
else
{
SBUF =0XFF;
while(TI ==0);
TI =0;
}
}
}
void display()
{
switch(j)
{
case 0:
P2 =PortN[ThB];
P1 =0x08;
j++;
break;
case 1:
P2 =PortN[SeB];
P1 =0X04;
j++;
break;
case 2:
P2 =PortN[FiB];
P1 =0X02;
j++;
break;
case 3:
P2 =PortN[ZeB];
P1 =0X01;
j =0;
break;
default:
j =0;
break;
}
}
void main()
{
P1 =0x00;
initialize();
receive(buf);
TMOD =TMOD|0X01;
TH0 =0XFE; //定时器初始化
TL0 =0X0C; //定时时间为1MS
//IE =0X8A; //开中断
IE =0X82;
TR0 =1; //启动定时
ThB =buf[0]; //接收到的数据赋给变量,用于显示。
SeB =buf[1];
FiB =buf[2];
ZeB =buf[3];
while(1)
{
if(Bdisplay ==1)
{
Bdisplay =0;
P1 =0XFF;
display();
}
}
}
呵呵~~大家不要鄙视~~~刚入门~~~
[em04] |
|