標(biāo)題:
PC機與單片機通信程序(RS232 協(xié)議)
[打印本頁]
作者:
wlz1972
時間:
2022-9-16 07:19
標(biāo)題:
PC機與單片機通信程序(RS232 協(xié)議)
單片機串口通信的應(yīng)用,通過串口,我們的個人電腦和單片機系統(tǒng)進(jìn)行通信。
個人電腦作為上位機,向下位機單片機系統(tǒng)發(fā)送十六進(jìn)制或者ASCLL碼,單片機
系統(tǒng)接收后,用LED顯示接收到的數(shù)據(jù)和向上位機發(fā)回原樣數(shù)據(jù)。
程序和原理圖見附件。
單片機源程序如下:
#include "reg52.h" //包函8051 內(nèi)部資源的定義
unsigned char dat; //用于存儲單片機接收發(fā)送緩沖寄存器SBUF里面的內(nèi)容
unsigned char fan;
int i,j;
void Delay() //延時程序
{
for(i=0; i<100; i++)
for(j=0; j<100; j++);
}
void delays()
{
int k;
for (k=0;k<1200;k++);
}
///////功能:串口初始化,波特率9600,方式1/////////
void Init_Com(void)
{
TMOD = 0x20;
PCON = 0x00;
SCON = 0x50;
TH1 = 0xFd;
TL1 = 0xFd;
TR1 = 1;
}
/////主程序功能:實現(xiàn)接收數(shù)據(jù)并把接收到的數(shù)據(jù)原樣發(fā)送回去///////
void main()
{
Init_Com();//串口初始化
while(1)
{
if ( RI ) //掃描判斷是否接收到數(shù)據(jù),
{
dat = SBUF; //接收數(shù)據(jù)SBUF賦與dat
if(dat==0x30) //如果PC發(fā)送十六進(jìn)制00,單片機P1口全亮。
{P1=0x00;
Delay(); }
else if(dat==0x31)
{P1=0x01;
Delay();}
else if(dat==0x32)
{P1=0x03;
Delay();}
else if(dat==0x33)
{P1=0x07;
Delay(); }
else if(dat==0x34)
{P1=0x0f;
Delay(); }
else if(dat==0x35)
{P1=0x1f;
Delay();}
else if(dat==0x06)
{P1=0x3f;
Delay(); }
else if(dat==0x07)
{P1=0x7f;
Delay();}
else if(dat==0x08)
{P1=0xff;
Delay(); }
else if(!(P2&0x01))
{ delays();
while(!(P2&0x01));
fan = 0x36;}
else if(!(P2&0x02))
{ delays();
while(!(P2&0x02));
fan = 0x37;}
else if(!(P2&0x04))
{ delays();
while(!(P2&0x04));
fan = 0x38;}
else if(!(P2&0x08))
{ delays();
RI=0; //RI 清零。
SBUF =dat; //在原樣把數(shù)據(jù)發(fā)送回去(接收數(shù)據(jù)為發(fā)送數(shù)據(jù)的ASCII碼,如發(fā)送q顯示為113)
}
}
}
復(fù)制代碼
PC 機與單片機通信(RS232 協(xié)議).doc
2022-9-16 07:18 上傳
點擊文件名下載附件
下載積分: 黑幣 -5
181 KB, 下載次數(shù): 15, 下載積分: 黑幣 -5
歡迎光臨 (http://www.torrancerestoration.com/bbs/)
Powered by Discuz! X3.1