注意波特率是9600功能:電腦通過串口給單片機發(fā)一個字節(jié),單片機收到后又給電腦發(fā)回去
#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;//暫時關(guān)閉接收
flag=0;
SBUF=temp;
while(!TI);//等待發(fā)送完畢
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;
}
本文引用地址:
http://butianyuan.cn/article/201611/320608.htm
//======聲明======
#include
unsigned char Read_Keyboard();
void RS232_SendData(unsigned char Sdata);
//======延遲函數(shù)======
void delay(unsigned int t)
{
for(;t>0;t--); //延遲循環(huán)
}
//======UART初始化函數(shù)=====
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;
}
//======主函數(shù)============
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;
}
}
}
//===========發(fā)送數(shù)據(jù)函數(shù)========
void RS232_SendData(unsigned char Sdata)
{
SBUF=Sdata; //發(fā)送數(shù)據(jù)
while(TI==0); //等待發(fā)送結(jié)束
TI=0; //清除發(fā)送結(jié)束標志
}
//========讀取按鍵函數(shù)==========
unsigned char Read_Keyboard()
{
unsigned char Keys_Value; //定義按鍵變量
unsigned char Keys_Temp;
do
{
P1=0xff; //P2口置高,準備讀取按鍵狀態(tài)
Keys_Temp=P1; //讀取按鍵狀態(tài)
delay(150); //消抖延時
P1=0xff; //P2口置高,準備讀取按鍵狀態(tài)
Keys_Value=P1; //讀取按鍵狀態(tài)
}
while(Keys_Value!=Keys_Temp); //如果讀狀態(tài)不一致,則重復(fù)讀取鍵值
return Keys_Value; //返回按鍵狀態(tài)值
}
評論