KEIL5超声波测距怎么写代码
时间: 2023-07-10 19:26:23 浏览: 148
超声波测距代码
KEIL5超声波测距的代码可以分为以下几步:
1. 定义相应的引脚和变量
```
sbit Ultrasonic_trig = P1^0;
sbit Ultrasonic_echo = P1^1;
unsigned int distance;
```
2. 初始化超声波引脚
```
Ultrasonic_trig = 0;
Ultrasonic_echo = 0;
```
3. 发送超声波信号
```
Ultrasonic_trig = 1;
delay_us(10);
Ultrasonic_trig = 0;
```
4. 接收超声波信号并计算距离
```
while(!Ultrasonic_echo);
TR0 = 1;
while(Ultrasonic_echo);
TR0 = 0;
distance = TH0*256+TL0;
distance = distance/58;
```
完整代码如下所示:
```
#include<reg52.h>
sbit Ultrasonic_trig = P1^0;
sbit Ultrasonic_echo = P1^1;
unsigned int distance;
void Ultrasonic_init(void)
{
Ultrasonic_trig = 0;
Ultrasonic_echo = 0;
TMOD = 0x01;
TH0 = 0;
TL0 = 0;
}
void Ultrasonic_measure(void)
{
Ultrasonic_trig = 1;
delay_us(10);
Ultrasonic_trig = 0;
while(!Ultrasonic_echo);
TR0 = 1;
while(Ultrasonic_echo);
TR0 = 0;
distance = TH0*256+TL0;
distance = distance/58;
}
void delay_us(unsigned int us)
{
while(us--)
{
_nop_();
_nop_();
_nop_();
_nop_();
}
}
void main()
{
Ultrasonic_init();
while(1)
{
Ultrasonic_measure();
}
}
```
阅读全文