-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathultrasound.cpp
More file actions
65 lines (51 loc) · 1.27 KB
/
ultrasound.cpp
File metadata and controls
65 lines (51 loc) · 1.27 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
#include "GrowduinoFirmware.h"
unsigned long timeStart;
unsigned long timeIn;
unsigned long timeOut;
int state;
long timetocm(long mtime) {
if (mtime > 0) {
return mtime / 27 / 2 ;
} else return 0;
}
int clip(long value) {
if (value > 32000) value = 32000;
return (int) lrint(value);
}
long ultrasound_ping_inner(int trigger, int echo) {
pinMode(trigger, OUTPUT);
pinMode(echo, INPUT);
state = LOW;
digitalWrite(trigger, LOW);
delayMicroseconds(2);
digitalWrite(trigger, HIGH);
delayMicroseconds(10);
digitalWrite(trigger, LOW);
timeStart = micros();
while (state == LOW && (micros() - timeStart < 40000)) {
state = digitalRead(echo);
}
timeIn = micros();
while (state == HIGH && (micros() - timeStart < 40000)) {
state = digitalRead(echo);
}
timeOut = micros();
if (timeOut - timeStart >= 40000) {
return MINVALUE;
}
return timetocm(timeOut - timeIn);
}
int ultrasound_ping() {
long r = ultrasound_ping(USOUND_TRG, USOUND_ECHO);
if (r > 30000) return 30000;
return (int) r;
}
long ultrasound_ping(int trigger, int echo) {
long distance;
distance = MINVALUE;
for (int i = 0; (i < 3 && distance == MINVALUE) ; i++) {
delay(10);
distance = ultrasound_ping_inner(trigger, echo);
}
return distance;
}