51单片机超声波测距

Echo是P3.2;

Trig是P3.7;

外部中断是P3.2;


源码:

#include

#define uint unsigned int

void reset();    		//初始化函数
void chufa();    		//触发信号函数
void open();    		//等待返回信号,有信号开启定时器
int seven();    		//测量七次并排序
void display(uint x);   //数码管显示函数
void time0();    		//定时器中断程序
void intr0();    		//外部中断程序
void delay(uint z);    	//延时函数

sbit echo = P3^2;
sbit trig = P3^7;
sbit int0 = P3^2;

uint t1,t0 = 0;

void main()
{
	reset();
	while(1)
	{
		seven();		
		display(seven());
	}
}

void reset()    //初始化函数
{
	echo = 0;
	trig = 0;
	TMOD = 0x11;
	EA = 1;
	ET0 = 1;
	TH0 = (65535-100)/256;
	TL0 = (65535-100)%256;
	IT0 = 1;
}



void chufa()    //触发信号函数
{
	trig = 1;
	delay(1);
	trig = 0;
}



void open()    //等待返回信号,有信号开启定时器
{
	while(!echo);
	EX0 = 1;
	TR0 = 1;

}



void time0() interrupt 1    //定时器中断程序
{
	TH0 = (65535-100)/256;
	TL0 = (65535-100)%256;
	t0++;
}


void intr0() interrupt 0    //外部中断程序
{
	TR0 = 0;
	t1 = t0*1.75;									
	t0 = 0;
	int0 = 1;
}



void display(uint x)    //数码管显示函数
{
	int ge,shi,a[10]={0xC0,0xF9,0xA4,0xB0,0x99,0x92,0x82,0xF8,0x80,0x90};
	ge = x % 10;
	shi = (x - ge)/10; 
	P2 = 0xFE;
    P0 = a[shi];
    delay(2);
    P2 = 0xFD;
    P0 = a[ge];
    delay(2);
}



void delay(uint z)    //延时函数
{																							   
    uint i,j;
    for(i=z;i>0;i--)
        for(j=110;j>0;j--);
}



int seven()    //测量七次并排序
{
	int i,j,f,del,c[7];
	for(f = 0;f <7;f++)
	{
		chufa();
		open();
		while(echo);
		c[f] = t1;
		delay(1);
	}

    for(i = 0;i < 6;i++)    //冒泡排序 
    {    
        for(j = 0;j < 6 - i;j++) 
            if(c[j] > c[j+1])   
            {    
                int temp = c[j];
                c[j] = c[j+1];    
                c[j+1] = temp;                            
            }              
    }

    del = (c[1]+c[2]+c[3]+c[4]+c[5])/5;
    return (del);
}

你可能感兴趣的:(51单片机)