I hava a Java-controlled robot. It has an ultrasonic sensor that is rotated back and forth by Motor B.
Normally, I have a separate thread that scans the environment and sends the collected data to another machine in order to draw a map.
However, sometimes the main thread needs to briefly use the sensor to look in a specific direction.
Here's my scanner thread:
public void run() {
while (!stop) {
Motor.B.forward();
while (Motor.B.getTachoCount() < 90 && !stop) {
try{Thread.sleep(20);} catch (InterruptedException ex) {ex.printStackTrace();}
Mapperbot.sendCommand("S US "+sonic.getDistance()+" "+Motor.B.getTachoCount());
}
Motor.B.backward();
while (Motor.B.getTachoCount() > -90 && !stop) {
try{Thread.sleep(10);} catch (InterruptedException ex) {ex.printStackTrace();}
}
}
Motor.B.stop();
}
And here's the "tell me the direction now" function, it belongs to the same class:
public synchronized int getDistanceInDirection(int direction) {
Motor.B.rotateTo(direction);
return sonic.getDistance();
}
The required behavior: Whenever "getDistanceInDirection" is called, it must briefly stop scanning and turn to the given direction, return the distance, and continue scanning.
What is the correct way to tell my scanner thread for the time it takes to execute the second function?