嵌入式学习笔记(一):超声波模块HC-SR04

#include 
#include "uart.h"
#include 

sbit Echo=P1^0;             		
sbit Trig=P1^1;
unsigned int time=0;

void starttime()
{
	TH0=0;
	TL0=0;
	TR0=1;	
}
void endtime()
{
	TR0=0;	
}
int get_time()
{
	unsigned int time;
	time=TH0 <<8 | TL0;
	return time;
}
void Delay10us()
{
	//设置16位定时器
	TMOD|=0x1;										
	TH0=0xff;
	TL0=0xf6;
	//启动定时器
	TR0=1;	
	//TF0定时器中断溢出标志位,溢出退出死循环										   
	while(!TF0);									     
	TF0=0;
}
//初始化超声波模块
void CSB_Init()
{
	Trig=0;
	Echo=0;	
	Trig=1;
	Delay10us();					  
	Trig=0;
}
//得到一次超声波测距的距离
float getdis()
{				 
	float distance;
	distance=time*0.017;
	return distance;
}
int main()
{	
	int i=0;
 	float dis;
 	
	while(1)
	{
		CSB_Init();
		//Echo=1时,开启定时器计时
		while(Echo!=1);
		starttime();
		//Echo=0时:结束定时器计时
		while(Echo!=0);
		endtime();	
		time=get_time();
		dis=getdis();
		printf(buf,"getdis=%fcm\r\n",dis);
	}
	return 0;				   
}

你可能感兴趣的:(嵌入式)