51单片机超声波测距代码
时间: 2023-07-23 09:23:17 浏览: 45
以下是基于51单片机的超声波测距代码,供参考:
```c
#include <reg52.h>
sbit Trig = P1^0;
sbit Echo = P1^1;
sbit Led = P2^0;
unsigned int distance;
void delay_us(unsigned int t)
{
while(t--);
}
void delay_ms(unsigned int t)
{
while(t--)
{
delay_us(1000);
}
}
void Init_Timer0(void)
{
TMOD = 0x01;
TH0 = 0xFC;
TL0 = 0x18;
TR0 = 1;
}
void Timer0_ISR(void) interrupt 1
{
distance = (unsigned int)(TH0 << 8) + TL0;
Led = 1;
delay_us(10);
Led = 0;
TH0 = 0;
TL0 = 0;
TR0 = 0;
}
void main()
{
Init_Timer0();
while(1)
{
Trig = 1;
delay_us(10);
Trig = 0;
while(!Echo);
TR0 = 1;
while(Echo);
distance = distance / 58;
if(distance < 30)
{
Led = 1;
}
else
{
Led = 0;
}
delay_ms(100);
}
}
```
该代码使用Timer0中断来测量超声波的回响时间,从而计算出距离。在主函数中,每隔100ms测量一次距离,并根据距离值控制LED灯的亮灭。注意,在使用该代码时需要根据实际情况对超声波模块的Trig和Echo引脚进行连接。
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)