注意波特率是9600
功能:电脑通过串口给单片机发一个字节,单片机收到后又给电脑发回去
、#include
#define uchar unsigned char
#define uint unsigned int
uint temp;
bit flag;
void init_ser1();
main()
{
init_ser1();
while(1)
{
if(RI==1)
{
P1=SBUF;
RI=0;
}
if(flag==1)
{
ES=0;//暂时关闭接收
flag=0;
SBUF=temp;
while(!TI);//等待发送完毕
TI=0;
ES=1;
}
}
}
void sel() interrupt 4
{
RI=0;
P1=SBUF;
temp=SBUF;
flag=1;
}
void init_ser1()
{
REN=1;
SM0=0;
SM1=1;
TMOD=0x20;
TH1=0xFD;
TL1=0xFD;
EA=1;
TR1=1;
ES=1;
}
//======声明======
#include
unsigned char Read_Keyboard();
void RS232_SendData(unsigned char Sdata);
//======延迟函数======
void delay(unsigned int t)
{
for(;t>0;t--); //延迟循环
}
//======UART初始化函数=====
void RS232_Init()
{
SCON=0x50; //0101 0000 UART工作模式1,REN=1(本位为串行接收启用位1:开始接收 0:停止接收)
TMOD=0x20; //0010 0000 Timer1 工作模式2
PCON=0x80; //SMOD1=1
TH1=0xfa; //波特率9600 bps at 11.0592MHZ
TL1=0xfa; //波特率9600 bps at 11.0592MHZ
TR1=1;
}
//======主函数============
void main()
{
unsigned char Keyboard_Status=0xff; //定义按键
RS232_Init(); // 初始化UART
while(1)
{
Keyboard_Status=Read_Keyboard()|0xf0; //读取按键值(屏蔽高4位)
//
switch(Keyboard_Status)
{
case ~0x01:RS232_SendData('A');break;
case ~0x02:RS232_SendData('B');break;
case ~0x04:RS232_SendData('C');break;
case ~0x08:RS232_SendData('D');break;
default:RS232_SendData('X');break;
}
}
}
//===========发送数据函数========
void RS232_SendData(unsigned char Sdata)
{
SBUF=Sdata; //发送数据
while(TI==0); //等待发送结束
TI=0; //清除发送结束标志
}
//========读取按键函数==========
unsigned char Read_Keyboard()
{
unsigned char Keys_Value; //定义按键变量
unsigned char Keys_Temp;
do
{
P1=0xff; //P2口置高,准备读取按键状态
Keys_Temp=P1; //读取按键状态
delay(150); //消抖延时
P1=0xff; //P2口置高,准备读取按键状态
Keys_Value=P1; //读取按键状态
}
while(Keys_Value!=Keys_Temp); //如果读状态不一致,则重复读取键值
return Keys_Value; //返回按键状态值
}