0

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?

user1582024
  • 715
  • 1
  • 6
  • 15
  • 1
    Are the robot commands like `Motor.B.forward()` or `Motor.B.rotateTo(...)` blocking or asynchronous? (I.e. does `rotateTo` wait until the robot has finished its rotation, or does it return immediately)? – isnot2bad Jul 22 '14 at 15:58

2 Answers2

0

I would use a semaphore:

final Semaphore semaphore = new Semaphore(1);

//in the scanner thread
semaphore.acquire();
try {
    while (! stop) {
        semaphore.release();
        semaphore.acquire();
        ...use sensor...
} finally {
    semaphore.release();
}

//in the main thread
semaphore.acquire();
try {
    ...use sensor...
} finally {
    semaphore.release();
}
Solomon Slow
  • 25,130
  • 5
  • 37
  • 57
0

Throw in a synchronized(this)

public void run() {
    while (!stop) {
        synchronized(this) {
            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();
}

Which will then ensure that the loop contents and getDistanceInDirection never run simultaneously

Eric
  • 95,302
  • 53
  • 242
  • 374