实现目标
1、巩固串口收发;
2、具体实现目标:(1)单片机A按下K1发送0x55给单片机B,单片机B收到后,点亮LED1;单片机B按下K2发送0x66给单片机A,单片机A收到后,点亮LED2.
一、硬件连接
二、程序设计
2.1 单片机A程序
cpp
#include <REGX52.H>
#define FOSC 11059200L //System frequency
#define BAUD 9600 //UART baudrate
sbit LED1 = P2^0;
sbit K1 = P1^0;
int num;
void Uart_send(unsigned char dat);
void Uart_send_str(unsigned char *p);
void Delay500ms();
void main()
{
PCON &= 0x7F; //波特率不倍速
SCON = 0x50; //8-bit variable UART
TMOD = 0x20;//0010 0000 //Set Timer1 as 8-bit auto reload mode
TH1 = TL1 = -(FOSC/12/32/BAUD); //Set auto-reload vaule
TR1 = 1; //Timer1 start run
ES = 1; //Enable UART interrupt
EA = 1; //Open master interrupt switch
while(1)
{
if(K1 ==0)
{
while(!K1);
Uart_send(0x55);
}
if(num == 0x66)
{
LED1 = 0;
}
}
}
void Uart_send(unsigned char dat)
{
SBUF = dat;
while(!TI);
TI = 0;
}
void Uart_send_str(unsigned char *p)
{
while(*p!='\0')
{
Uart_send(*p);
p++;
}
}
void Uart_Isr() interrupt 4
{
if (RI == 1)
{
RI = 0; //Clear receive interrupt flag
num = SBUF; //
}
}
void Delay500ms() //@11.0592MHz
{
unsigned char i, j, k;
i = 4;
j = 129;
k = 119;
do
{
do
{
while (--k);
} while (--j);
} while (--i);
}
2.2 单片机B程序
cpp
#include <REGX52.H>
#define FOSC 11059200L //System frequency
#define BAUD 9600 //UART baudrate
sbit LED2 = P2^0;
sbit K2 = P1^0;
int num;
void Uart_send(unsigned char dat);
void Uart_send_str(unsigned char *p);
void Delay500ms();
void main()
{
PCON &= 0x7F; //波特率不倍速
SCON = 0x50; //8-bit variable UART
TMOD = 0x20;//0010 0000 //Set Timer1 as 8-bit auto reload mode
TH1 = TL1 = -(FOSC/12/32/BAUD); //Set auto-reload vaule
TR1 = 1; //Timer1 start run
ES = 1; //Enable UART interrupt
EA = 1; //Open master interrupt switch
while(1)
{
if(K2 ==0)
{
while(!K2);
Uart_send(0x66);
}
if(num == 0x55)
{
LED2 = 0;
}
}
}
void Uart_send(unsigned char dat)
{
SBUF = dat;
while(!TI);
TI = 0;
}
void Uart_send_str(unsigned char *p)
{
while(*p!='\0')
{
Uart_send(*p);
p++;
}
}
void Uart_Isr() interrupt 4
{
if (RI == 1)
{
RI = 0; //Clear receive interrupt flag
num = SBUF; //
}
}
void Delay500ms() //@11.0592MHz
{
unsigned char i, j, k;
i = 4;
j = 129;
k = 119;
do
{
do
{
while (--k);
} while (--j);
} while (--i);
}