最簡單的超聲波測距程序之一
S=(time*1.893)/100; 中的1.893可調
#include <AT89x51.H> //器件配置文件
#include <intrins.h>
#include "sanxian.h"
#define RX P1_0
#define TX P1_2
#define uchar unsigned char
#define uint unsigned int
unsigned int time=0;
unsigned int timer=0;
unsigned char posit=0;
unsigned long S=0;
bit flag =0;
sbit key=P1^6;
unsigned char const discode[] ={ 0xC0,0xF9,0xA4,0xB0,0x99,0x92,0x82,0xF8,0x80,0x90,0xBF,0xff/*-*/};
unsigned char const positon[4]={ 0xfe,0xfd,0xfb,0xf7};
unsigned char disbuff[4] ={ 0,0,0,0,};
/********************************************************/
void Display(void) //掃描數碼管
{
if(posit==0)
{P0=(discode[disbuff[posit]])&0x7f;}
else
{P0=discode[disbuff[posit]];}
P3=positon[posit];
if(++posit>=3)
posit=0;
}
/********************************************************/
void Conut(void)
{
time=TH0*256+TL0;
TH0=0;
TL0=0;
S=(time*1.893)/100; //算出來是CM
if((S>=700)||flag==1) //超出測量范圍顯示“-”
{
flag=0;
disbuff[0]=10; //“-”
disbuff[1]=10; //“-”
disbuff[2]=10;
disbuff[3]=10; //“-”
}
else
{
disbuff[0]=S%1000/100;
disbuff[1]=S%1000%100/10;
disbuff[2]=S%1000%10 %10;
}
}
/********************************************************/
void zd0() interrupt 1 //T0中斷用來計數器溢出,超過測距范圍
{
flag=1; //中斷溢出標志
}
/********************************************************/
void zd3() interrupt 3 //T1中斷用來掃描數碼管和計800MS啟動模塊
{
TH1=0xf8;
TL1=0x30;
Display();
timer++;
if(timer>=400)
{
timer=0;
TX=1; //800MS 啟動一次模塊
_nop_();
_nop_();
_nop_();
_nop_();
_nop_();
_nop_();
_nop_();
_nop_();
_nop_();
_nop_();
_nop_();
_nop_();
_nop_();
_nop_();
_nop_();
_nop_();
_nop_();
_nop_();
_nop_();
_nop_();
_nop_();
TX=0;
}
}
/*********************************************************/
void Delay(uint i) //延時函數
{
uint k,j; //延時參數
for(k=i; i>0; i--)
for(j=110; j>0; j--);
}
void main( void )
{ uchar i=0;
init_WT588D(); //定義接收緩沖區
Delay(100);
TMOD=0x11; //設T0為方式1,GATE=1;
TH0=0;
TL0=0;
TH1=0xf8; //2MS定時
TL1=0x30;
ET0=1; //允許T0中斷
ET1=1; //允許T1中斷
TR1=1; //開啟定時器
EA=1; //開啟總中斷
disbuff[0]=S%1000/100;
disbuff[1]=S%1000%100/10;
disbuff[2]=S%1000%10 %10;
while(1)
{
while(!RX); //當RX為零時等待
TR0=1; //開啟計數
while(RX); //當RX為1計數并等待
TR0=0; //關閉計數
Conut(); //計算 Line_3A(disbuff[0]);
Delay_1ms(1200);
Line_3A(disbuff[1]+1);
Delay_1ms(1200);
Line_3A(disbuff[2]+11);
Delay_1ms(1200);
}
|