P10,P11,P12為位選,采用共陽數(shù)碼管顯示。精確到CM級別。tring為發(fā)射控制,本程序定義為P20引腳。 echo接外部中斷0.
#include <reg52.h>
#include <reg52.h>
sbit wei_ge=P1^0;
sbit wei_shi=P1^1;
sbit wei_bai=P1^2;
sbit a=P2^3;
#define uchar unsigned char
#define uint unsigned int
int time;
int succeed_flag;
uchar timeL;
uchar timeH;
sbit Trig=P2^0;
sbit Echo=P3^2;
uchar code table[]={0xc0,0xf9,0xa4,0xb0,0x99,0x92,0x82,0xf8,0x80,0x90,0x88,0x83,0xc6,0xa1,0x86,0x8e};
void delay(uint z)
{
uint x,y;
for(x=z;x>0;x--)
for(y=110;y>0;y--);
}
void delay_20us()
{
uchar a ;
for(a=0;a<100;a++);
}
//顯示數(shù)據(jù)轉(zhuǎn)換程序
void display(uint temp)
{
uchar ge,shi,bai;
bai=temp/100;
shi=(temp%100)/10;
ge=temp%10;
P0=table[ge]; //送數(shù)字8到段碼端口
wei_ge=0;
delay(5);
// P0=table[shi];
// wei_shi=0;
// delay(5);
// P0=table[bai]; //送數(shù)字8到段碼端口
// wei_bai=0;
// delay(5);
if(temp>150)
a=0;
else
a=1;
}
void main()
{
uint distance;
Trig=0; //首先拉低脈沖輸入引腳
EA=1; //打開總中斷0
TMOD=0x10; //定時器1,16位工作方式
while(1)
{
EA=0; //關(guān)總中斷
Trig=1; //超聲波輸入端
delay_20us(); //延時20us
Trig=0; //產(chǎn)生一個20us的脈沖
while(Echo==0); //等待Echo回波引腳變高電平
succeed_flag=0; //清測量成功標志
EA=1;
EX0=1; //打開外部中斷0
TH1=0; //定時器1清零
TL1=0; //定時器1清零
TF1=0; //計數(shù)溢出標志
TR1=1; //啟動定時器1
delay(10); //等待測量的結(jié)果
TR1=0; //關(guān)閉定時器1
EX0=0; //關(guān)閉外部中斷0
if(succeed_flag==1)
{
time=timeH*256+timeL;
distance=time*0.0172; //厘米
}
if(succeed_flag==0)
{
distance=0; //沒有回波則清零
}
display(distance);
}
}
//外部中斷0,用做判斷回波電平
void exter() interrupt 0 // 外部中斷0是0號
{
EX0=0; //關(guān)閉外部中斷
timeH =TH1; //取出定時器的值
timeL =TL1; //取出定時器的值
succeed_flag=1;//至成功測量的標志
}
//定時器1中斷,用做超聲波測距計時
void timer1() interrupt 3 //
{
TH1=0;
TL1=0;
}