標題:
單片機與PC通信程序
[打印本頁]
作者:
123321gjx
時間:
2021-4-10 19:31
標題:
單片機與PC通信程序
/* 名稱:單片機與PC通信
說明:單片機可接收PC發(fā)送的數(shù)字字符,按下單片機的K1鍵后,單片機可向PC發(fā)送字符串。在Proteus環(huán)境下完成本實驗時,需要安裝Virtual Serial Port Driver和串口調(diào)試助手。本例緩沖100個數(shù)字字符,緩沖滿后新數(shù)字從前面開始存放(環(huán)形緩沖)。
*/
#include<reg51.h>
#define uchar unsigned char
#define uint unsigned int
uchar Receive_Buffer[101]; //接收緩沖
uchar Buf_Index=0; //緩沖空間索引
//數(shù)碼管編碼
uchar code DSY_CODE[]={0x3f,0x06,0x5b,0x4f,0x66,0x6d,0x7d,0x07,0x7f,0x6f,0x00};
//延時
void DelayMS(uint ms)
{
uchar i;
while(ms--) for(i=0;i<120;i++);
}
//主程序
void main()
{
uchar i;
P0=0x00;
Receive_Buffer[0]=-1;
SCON=0x50; //串口模式1,允許接收
TMOD=0x20; //T1工作模式2
TH1=0xfd; //波特率9600
TL1=0xfd;
PCON=0x00; //波特率不倍增
EA=1;EX0=1;IT0=1;
ES=1;IP=0x01;
TR1=1;
while(1)
{
for(i=0;i<100;i++)
{ //收到-1為一次顯示結(jié)束
if(Receive_Buffer[ i]==-1) break;
P0=DSY_CODE[Receive_Buffer[ i]];
DelayMS(200);
}
DelayMS(200);
}
}
//串口接收中斷函數(shù)
void Serial_INT() interrupt 4
{
uchar c;
if(RI==0) return;
ES=0; //關(guān)閉串口中斷
RI=0; //清接收中斷標志
c=SBUF;
if(c>='0'&&c<='9')
{ //緩存新接收的每個字符,并在其后放-1為結(jié)束標志
Receive_Buffer[Buf_Index]=c-'0';
Receive_Buffer[Buf_Index+1]=-1;
Buf_Index=(Buf_Index+1)%100;
}
ES=1;
}
void EX_INT0() interrupt 0 //外部中斷0
{
uchar *s="這是由8051發(fā)送的字符串!\r\n";
uchar i=0;
while(s[i]!='\0')
{
SBUF=s[i];
while(TI==0);
TI=0;
i++;
}
}
復(fù)制代碼
歡迎光臨 (http://www.torrancerestoration.com/bbs/)
Powered by Discuz! X3.1