|
![](static/image/common/ico_lz.png)
楼主 |
发表于 2013-6-17 19:46:53
|
显示全部楼层
#include<reg51.h>
#include<intrins.h>
sbit Send=P1^0;
sbit Rece=P1^1;
bit Over_flag=0;
#define uchar unsigned char
#define uint unsigned int
#define u16 unsigned char
uchar code segtab[]={0xc0,0xf9,0xa4,0xb0,0x99,0x92,0x82,0xf8,0x80,
0x90,0x88,0x83,0xc6,0xa1,0x86,0x8e,0x8c,0xff};
uchar dbuf[]={1,3,2,4};
void Delay_ms(uchar time)
{
uchar i;
while(time--)
for(i=0;i<200;i++);
}
void Disp_Led(void)
{
uchar i,Bsel;
Bsel=0x10;
for(i=0;i<4;i++)
{
P0=Bsel;
P2=0xdf;
P2=0x00;
P0=segtab[dbuf[i]];
P2=0xff;
Delay_ms(1);
Bsel=_crol_(Bsel,1);
P0=0xff;
P2=0x00;
}
}
/*******************************************************************
程序说明:产生一40Khz频率
参数说明:无
返回说明:无
********************************************************************/
void Send_40khz(void)
{
Send=~Send;
_nop_();
_nop_();
_nop_();
_nop_();
_nop_();
_nop_();
_nop_();
_nop_();
_nop_();
_nop_();
_nop_();
_nop_();
}
/*******************************************************************
程序说明:分解所测距离送显
参数说明:无
返回说明:无
********************************************************************/
void Rang_div(u16 value)
{
dbuf[0]=value/1000;
dbuf[1]=value/100%10;
dbuf[2]=value/10%10;
dbuf[3]=value%10;
}
/*******************************************************************
程序说明:测量距离溢出
参数说明:无
返回说明:无
*******************************************************************/
void Timer0(void)interrupt 1
{
Over_flag=1; //设置溢出标志
}
/*******************************************************************
程序说明:每隔12.5ms将重新发送一次声波。
参数说明:无
返回说明:无
*******************************************************************/
void Timer1(void)interrupt 3
{
static uchar Count=0;
uchar i;
Count++;
if(Count==50)
{
Count=0;
for(i=0;i<5;i++) //发送5个40Khz波形
{
Send_40khz();
}
TR0=1; //启动定时器1来计数距离
Send=1;
}
}
/*******************************************************************
程序说明:超声波测量程序,通过控制定时器,并运用查询方式等待超声
波回波。读取定时器的值。根据声音在空气中的传播速度计算
出被测地的距离
参数说明:无
返回说明:返回一无符号整型,所测距离大于一个字符。
*******************************************************************/
uint Get_Rang(void)
{
uint Over_Time=0; //定义超时标志
uint Rangs;
float Time;
TR1=1; //开启定时器1来发送声波
while(Rece&&(Over_Time<2000))Over_Time++;//在额定时间内等待声波
EA=0; //表示接收到声波或者超时
TR0=0; //关闭定时器
TR1=0;
Time=TH0*256+TL0; //获取计数值
Rangs=Time*17/1000; //计算距离 0.034cm/us*time /
// / 2
if(Over_Time>1700||Over_flag||Rangs>400)//超时或大于5m或者定时器溢出
{
Rangs=0; //无距离
}
TH0=TL0=0; //清除各标志
Over_Time=0;
Over_flag=0;
return Rangs;
}
void main(void)
{
uint Rang;
uchar i;
TMOD=0x21; //定时器1来设置重复发送,定时器2计数时间
TH0=0;
TL0=0;
TH1=-250;
TL1=-250;
EA=1; //允许定时中断
ET0=1;
ET1=1;
while(1)
{
Rang=Get_Rang(); //获取距离
Rang_div(Rang); //分解获取距离
for(i=0;i<200;i++) //延时一段时间重新测量
Disp_Led();
EA=1; //开启定时器再次测量
}
}
|
|