stc89c52超声波测距代码
时间: 2023-11-23 18:06:16 浏览: 109
以下是STC89C52RC单片机智能小车超声波测距的代码,其中Trig连接P1.5,Echo连接P1.6,使用定时器1进行计时:
```c
#include <reg52.h>
#include <intrins.h>
#define uint unsigned int
#define uchar unsigned char
sbit Trig = P1^5;
sbit Echo = P1^6;
void delay_us(uint us)
{
while(us--)
{
_nop_();
_nop_();
_nop_();
_nop_();
}
}
void delay_ms(uint ms)
{
while(ms--)
{
delay_us(1000);
}
}
void Init_Timer1(void)
{
TMOD |= 0x10;
TH1 = 0;
TL1 = 0;
TR1 = 1;
}
uint Get_Distance(void)
{
uint distance;
Trig = 0;
delay_us(2);
Trig = 1;
delay_us(10);
Trig = 0;
while(!Echo);
TH1 = 0;
TL1 = 0;
while(Echo);
TR1 = 0;
distance = TH1 * 256 + TL1;
distance = distance / 58;
return distance;
}
void main()
{
uint distance;
Init_Timer1();
while(1)
{
distance = Get_Distance();
if(distance < 30)
{
P2 = 0x01;
}
else
{
P2 = 0x00;
}
delay_ms(100);
}
}
```
阅读全文