单片机串口通信实验
0x1 实验要求
(1)每隔1秒钟,A向B通过串口发送一个字节c_num(该字节按照0x00-0x09循环,例如某一时刻发送c_num=0x-3);
(2)B接收到数据后,做9-c_num的计算,并将计算结果通过串口发送给A单片机。例如B接收到0x03,则B要通过串口返回0x09-0x03=0x06给单片机A;
(3)A接收到数据后,将收到数据写在数码管上,例如显示收到的数字6;
(4)A和B的串口发送不要用中断方式,A的串口接收必须用中断方式,B的串口接收可用/不用串口中断。
0x2 电路原理图
0x3 代码部分
单片机A:
#include<reg51.h>
#define uchar unsigned char
uchar RIflag=0;
uchar RIreceive;
char code map[]={0x3f,0x06,0x5b,0x4f,0x66,0x6d,0x7d,0x07,0x7f,0x6f};
void delay(unsigned int time)
{
unsigned int j=0;
for(;time>0;time--)
for(j=0;j<125;j++);
}
void main(void)
{
uchar counter=0;
TMOD=0x20;
TH1=TL1=0xf4;
PCON=0;
SCON=0x50;
TR1=1;
EA=1;
ES=1;//打开中断
while(1)
{
SBUF=counter;
while(TI==0);
TI=0;//数据发送完成,标志位清零
if((RIflag==1)&&(RIreceive==counter))
{
P2=map[counter];
if(++counter>9)counter=0;
delay(500);
}
}
}
void zhongduan() interrupt 4
{
if(RI)
{
RI=0;
RIflag=1;
RIreceive=SBUF;
}
}
单片机B:
#include<reg51.h>
#define uchar unsigned char
char code map[]={0x3f,0x06,0x5b,0x4f,0x66,0x6d,0x7d,0x07,0x7f,0x6f};
void main(void)
{
uchar receive;
TMOD=0x20;
TH1=TL1=0xf4;
PCON=0;
SCON=0x50;
TR1=1;
while(1)
{
while(RI==1)
{
RI=0;
receive=SBUF;
SBUF=receive;
while(TI==0);
TI=0;
P2=map[9-receive];
}
}
}
本文来自博客园,作者:、晚风、,转载请注明原文链接:https://www.cnblogs.com/xgcl/p/14740206.html