51单片机双向通信实例

  通过甲机按键控制点亮乙机LED灯,通过控制乙机按键向甲机发送数字,并且使用数码管显示。

电路原理图:

在这里插入图片描述

甲机代码:

#include<reg51.h>
#define uchar unsigned char
#define uint unsigned int 

sbit LED1=P1^0;
sbit LED2=P1^3;
sbit K1=P1^7;
uchar Operation_No=0; //操作代码
//数码管代码
uchar code DSY_CODE[]={0x3f,0x06,0x5b,0x4f,0x66,0x6d,0x7d,0x07,0x7f,0x6f};

//延时
void DelayMS(uint ms)
{
	uchar i;
	while(ms--) 
	{
		for(i=0;i<120;i++);
	}
		
}
//向串口发送字符
void Putc_to_SerialPort(uchar c)
{
	SBUF=c; 
	while(TI==0); 
	TI=0; //TI硬件置1,软件清0
}
//主程序
void main()
{
	LED1=LED2=1; 
	P0=0x00;
	SCON=0x50;         //串口模式 1,允许接收
	TMOD=0x20;        //T1 工作模式 2
	PCON=0x00;         //波特率不倍增
	TH1=0xfd; 
	TL1=0xfd;   			//9600
	TI=RI=0;       //
	TR1=1;
	IE=0x90;        //允许串口中断
	while(1)
	{
		DelayMS(100);
		if(K1==0)       //按下 K1 时选择操作代码 0,1,2,3
		{
		while(K1==0); 
			{
				Operation_No=(Operation_No+1)%4;
			}
			
		 
		switch(Operation_No)   //根据操作代码发送 A/B/C 或停止发送
			{
				case 0:    Putc_to_SerialPort('X'); LED1=LED2=1;break;
				case 1:    Putc_to_SerialPort('A');LED1=~LED1;LED2=1;break;
				case 2:    Putc_to_SerialPort('B'); LED2=~LED2;LED1=1; break;
				case 3:    Putc_to_SerialPort('C'); LED1=~LED1;LED2=LED1; break;
			}
		}
	}
}
//甲机串口接收中断函数
void Serial_INT() interrupt    4
{
	if(RI)
	{
		RI=0;
		if(SBUF>=0&&SBUF<=9) 
		{
			P0=DSY_CODE[SBUF];
		}
			
		else 
		{
			P0=0x00;
		}
			
	}
}
 

乙机代码:

#include<reg51.h>
#define uchar unsigned char
#define uint unsigned int 
sbit LED1=P1^0;
sbit LED2=P1^3; 
sbit K2=P1^7; 
uchar NumX=-1;
//延时
void DelayMS(uint ms)
{
	uchar i;
	while(ms--) 
	{
		for(i=0;i<120;i++);
	}
		
}
//主程序
void main()
{
	LED1=LED2=1;
	SCON=0x50;         //串口模式 1,允许接收
	TMOD=0x20;        //T1 工作模式 2


	TH1=0xfd;            //波特率 9600
	TL1=0xfd;
	PCON=0x00;         //波特率不倍增
	RI=TI=0; 
	TR1=1; 
	IE=0x90; 
	while(1)
	{
		DelayMS(100);
		if(K2==0)
		{
			while(K2==0);
			NumX=++NumX;   //产生 0~10 范围内的数字,其中 10 表示关闭
			SBUF=NumX; 
			if(NumX==10)
			{
				NumX=-1;
			}
			while(TI==0); 
			TI=0; //TI硬件置1,软件清0
		}
	}
}
void Serial_INT() interrupt 4
{
	if(RI)      //如收到则 LED 则动作
	{
		RI=0;
		switch(SBUF) //根据所收到的不同命令字符完成不同动作
		{
			case 'X':  LED1=LED2=1;break;       //全灭
			case 'A':  LED1=0;LED2=1;break;    //LED1 亮 
			case 'B':  LED2=0;LED1=1;break;    //LED2 亮 
			case 'C':  LED1=LED2=0;            //全亮
		}
	}
}

效果截图:

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/weixin_45488643/article/details/105943734
今日推荐