51单片机超声波测距代码

超声波测距代码:

cpp 复制代码
#include<reg52.h>

sbit echo=P2^0 ; //回声接收端口
sbit trig=P2^1  ;//超声波触发端口

sbit wei1=P2^4;
sbit wei2=P2^5;
sbit wei3=P2^6;
sbit wei4=P2^7;

sbit in=P2^2;

#define dula P0
#define uchar unsigned char
#define uint unsigned int

long int distance=0;
uchar count;
unsigned char code table[]={0x3f,0x06,0x5b,0x4f,0x66,0x6d,0x7d,0x07,0x7f,0x6f,0x77,0x7c,0x39,0x5e,0x79,0x71};
unsigned char code table1[]={0xbf,0x86,0xdb,0xcf,0xe6,0xed,0xfd,0x87,0xff,0xef,0x71};

void delay(uint xms)
{
	uint i,j;
	for(i=xms;i>0;i--)
		for(j=112;j>0;j--);
}

void display(long int num)
{
	uchar qian,bai,shi,ge;
	if((num>5000)||(num==0))
	{
		 qian=15;
		 bai=15;
		 shi=10;
		 ge=15;
	}
	else
	{
		   qian=num/1000;
		   bai=(num/100)%10;
		   shi=(num/10)%10;
		   ge=num%10;
		   if(bai>0)
		   {
		   	   in=0;
		   }
		   else if(bai==0)
		   {
		   	   in=1;
		   }
	}

	wei1=1;
	wei2=0;
	wei3=0;
	wei4=0;
	P0=table[qian];
	delay(2);

	wei1=0;
	wei2=1;
	wei3=0;
	wei4=0;
	P0=table[bai];
	delay(2);

	wei1=0;
	wei2=0;
	wei3=1;
	wei4=0;
	P0=table1[shi];
	delay(2);

	wei1=0;
	wei2=0;
	wei3=0;
	wei4=1;
	P0=table[ge];
	delay(2);
}

void Init_timer0(void)
{
	 TMOD=0x01;
	 TL0=0x66;
	 TH0=0xfc;
	 ET0=1;
	 EA=1;
}

void Init_parameter(void)
{
 	 echo=0;
 	 trig=0;
 	 count=0;
 	 distance=0;
}

void Trig_SuperSonic(void) //发出声波
{
	 trig=1;
	 delay(1);
	 trig=0;
}

void Measure_Distance(void)
{
	uchar l;
	uint h,y;
	TR0=1;
	while(echo)
	{
		  ;
	}
	TR0=0;
	l=TL0;
	h=TH0;
	y=(h<<8)+1;
	y=y-0xfc66;
	distance=y+1000*count;
	TL0=0x66;
	TH0=0xfc;
	delay(30);
	distance=0.17*distance;
}

void main(void)
{
	uchar a;
	Init_timer0();
	Init_parameter();
	while(1)
	{
		 Trig_SuperSonic();
		 while(echo==0)
		 {
		 		;
		 }
		 Measure_Distance();
		 for(a=100;a>0;a--)
		 {
		 	 display(distance);
		 }
		  Init_parameter();
	}
}

void timer0(void)interrupt 1
{
	TF0=0;
	TL0=0x66;
	TH0=0xfc;
	count++;
	if(count==18)
	{
		 TR0=0;
		 TL0=0x66;
		 TH0=0xfc;
		 count=0;
	}
}
相关推荐
恒锐丰科技韩生15 小时前
RB6005A|晶准 单节锂电池内置 MOS 保护芯片 DFN2×3‑8
嵌入式硬件·硬件工程
Black_Rock_br18 小时前
ARM服务器固件FVP仿真开发流程深度解析实战指南
arm开发·人工智能·嵌入式硬件·硬件工程
恒锐丰科技林技术员21 小时前
SS8918T 微步进电机驱动芯片:高性能步进运动控制解决方案
经验分享·嵌入式硬件·硬件工程
爱吃汽的小橘2 天前
DC-DC BUCK电路
硬件工程
恒锐丰科技韩生3 天前
SS6625E|3.0‑20V 单通道 16A 峰值 H 桥直流电机驱动 SOP8 门锁玩具机器人专用
嵌入式硬件·硬件工程
单片机杂货铺4 天前
【单片机毕业设计选题】基于stm32单片机儿童公路车速度检测报警
stm32·单片机·嵌入式硬件·51单片机·硬件工程·课程设计
恒锐丰科技韩生4 天前
SS8844T|8.2‑40V 四通道独立半桥驱动 ETSSOP28 带散热焊盘 工业自动化机器人专用
嵌入式硬件·硬件工程
恒锐丰小瑞5 天前
率能SS6810H 32V/1A/双通道H桥驱动芯片,PWM电流控制与混合衰减模式,用于POS打印机/安防相机/机器人
嵌入式硬件·数码相机·机器人·硬件工程
恒锐丰科技林技术员5 天前
SS8812T 双通道 H 桥电机驱动芯片应用解析
经验分享·嵌入式硬件·硬件工程
恒锐丰-罗生5 天前
国产电机驱动 SS6635E|宽压大电流单通道 H 桥芯片全面总结
驱动开发·嵌入式硬件·硬件工程