-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathUltrasonicSensor.java
65 lines (45 loc) · 1.95 KB
/
UltrasonicSensor.java
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
65
package ca.uoit.crobot.hardware;
import com.pi4j.io.gpio.GpioPinDigitalInput;
import com.pi4j.io.gpio.GpioPinDigitalOutput;
import com.pi4j.io.gpio.PinState;
import static ca.uoit.crobot.hardware.GpioUtility.getDigitalInput;
import static ca.uoit.crobot.hardware.GpioUtility.getDigitalOutput;
public class UltrasonicSensor implements DistanceSensor {
public static final int DEFAULT_TRIGGER_TIME_NS = 10000;
private final int triggerPinAddress;
private final int echoPinAddress;
private final int triggerTimeNs;
private GpioPinDigitalOutput triggerPin;
private GpioPinDigitalInput echoPin;
public UltrasonicSensor(final int triggerPinAddress, final int echoPinAddress) {
this(triggerPinAddress, echoPinAddress, DEFAULT_TRIGGER_TIME_NS);
}
public UltrasonicSensor(final int triggerPinAddress, final int echoPinAddress, final int triggerTimeNs) {
this.triggerPinAddress = triggerPinAddress;
this.echoPinAddress = echoPinAddress;
this.triggerTimeNs = triggerTimeNs;
}
@Override
public synchronized int measure() {
if (triggerPin == null || echoPin == null)
throw new IllegalStateException("not initialized");
triggerPin.setState(PinState.HIGH);
long triggerStart = System.nanoTime();
while (triggerStart + triggerTimeNs > System.nanoTime());
triggerPin.setState(PinState.LOW);
long start = System.nanoTime();
while (echoPin.isLow())
start = System.nanoTime();
while (echoPin.isHigh());
long duration = System.currentTimeMillis() - start;
return (int) (duration / 58309.0);
}
@Override
public void init() {
triggerPin = getDigitalOutput(triggerPinAddress);
triggerPin.setShutdownOptions(true, PinState.LOW);
triggerPin.setState(PinState.LOW);
echoPin = getDigitalInput(echoPinAddress);
echoPin.setShutdownOptions(true, PinState.LOW);
}
}