学习目标
include “config.h”
define ULTRASONIC_ECHO P40
define ULTRASONIC_TRIG P13
define ULTRASONIC_PIN_INIT() {P1M1 &= ~0x08, P1M0 |= ~0x08, P4M1 &= ~0x01, P4M0 &= ~0x01;}
void Ultrasonic_init();
u8 Ultrasonic_get_distance(float *distance);
endif
```c
#include "Ultrasonic.h"
static void Delay10us() //@24.000MHz
{
unsigned char i;
i = 78;
while (--i);
}
void Ultrasonic_init() {
ULTRASONIC_PIN_INIT();
}
u8 Ultrasonic_get_distance(float *distance) {
u8 flag = 0;
u16 cnt = 20;
//////////////// 触发测距 /////////////////
ULTRASONIC_TRIG = 1;
Delay10us();
ULTRASONIC_TRIG = 0;
do {
Delay10us();
} while(--cnt);
do {
if(ULTRASONIC_ECHO == 1) {
if(flag == 0) {
cnt = 0;
flag = 1;
}
cnt++;
} else {
break;
}
Delay10us();
} while(cnt < 2360);
if(cnt <= 12 || cnt >= 2360) {
// 距离小或者超出
return 0;
}
// 340 m/s
// 340 m/ 1000 000us
// 10us = 340m/100000
// 10us == 1cnt
// m
*distance = cnt * 34.0 / 10000.0 / 2;
}
练习题
- 实现超声波测距驱动