7月 28

51单片机 超声波测距测试

我使用51单片机,超声波模块是hc-sr04。以前在raspberry上用python测的,这次因为需要转到51单片机上,所以用C语言重写,原理上基本一致。

#include 
#include 
typedef unsigned char uchar;
typedef unsigned int  uint;	
  

// 测试距离
uint S;
// 非中断用计时计数器
uint hcsr_count;
sbit Led = P1^5;
sbit Trig = P1^1;
sbit ECHO =P1^2;
sbit Led4 = P1^4;


// 超声波给20us的高电平
void delay_20us()
{
	uchar bt ;
	for(bt=0;bt<4;bt++);
}

main()
{
	uint count;
	uchar us50;
	Led = 0;
	Led4 = 0;
	Trig = 0;
	ECHO = 0;
	while(1)
	{
		hcsr_count = 0;
		// 开始20us的搞电平
		Trig = 1;
		delay_20us();
		Trig = 0;
		count = 0;
		//等待Echo回波引脚变高电平
		while(ECHO ==0 )  
		{
			_nop_();
		}
		// 开始接收
		while(ECHO == 1 )
		{
			for(us50=0;us50<10;us50++);
			hcsr_count++;
			// 如果获得范围大于两米
			// 则强制返回值
			if (hcsr_count >= 2357)
				ECHO = 1;
		}
		//算出来是CM。1.7 出处。 
		// 在空气中传播速度34000cm/s。
		// hcsr_count每次计数时间约为0.00005秒,既1/20000秒
		// 34000cm/s * (1/20000)s = 1.7cm/s
		// 统计出的为往返路程,除2后为单程
		S = (hcsr_count*1.7)/2;     //算出来是CM
		if(S < 20)
		{
			Led = 1;
		}																												   
		else if(S > 21)
		{
			Led = 0;
		}
	}
}

超声波测距源码