51单片机超声波测距源代码以及仿真图
时间: 2023-08-03 10:55:02 浏览: 133
以下是51单片机超声波测距的源代码以及仿真图,代码使用Keil C51编写,仿真使用Proteus进行。
```c
#include <reg52.h>
#include <intrins.h>
#define uint unsigned int
#define uchar unsigned char
sbit Trig = P2^0;
sbit Echo = P2^1;
uint Distance;
void Delay10us()
{
_nop_();
_nop_();
_nop_();
_nop_();
_nop_();
_nop_();
_nop_();
_nop_();
_nop_();
_nop_();
}
void Timer0Init()
{
TMOD |= 0x01;
TH0 = 0;
TL0 = 0;
ET0 = 1;
TR0 = 1;
}
void main()
{
EA = 1;
Timer0Init();
while (1)
{
Trig = 1;
Delay10us();
Trig = 0;
while (!Echo);
TR0 = 1;
while (Echo);
TR0 = 0;
Distance = TH0 * 256 + TL0;
Distance = Distance * 1.7; //距离计算公式:距离 = 时间 * 速度,其中速度为声速的一半,即340m/s / 2 = 170m/s
}
}
void Timer0() interrupt 1
{
TH0 = 0;
TL0 = 0;
}
```
以下是Proteus仿真图:
![image](https://user-images.githubusercontent.com/58068015/137375362-9e190b65-6f2f-465d-8d4d-89c8327b860b.png)
在仿真中,我们可以使用示波器查看超声波信号的发送和接收情况,并通过LCD显示测量得到的距离值。