javaif-statementtimerfinch

Timer on if statement?


I’m working on a Finch robot project on detecting objects and in one of the methods, I have to do an if statement for if the Finch has detected an object within 5 seconds, would I need a timer class for this? Please help. (New to Java)

IF Finch detects an object <= 5 seconds, stop and turn LED to blue ELSE wait 1 second and keep moving in random direction (I’ve already done this)

Edit: my code so far:

public static void ObjectEncountered() {

    while(true) {

        if(myfinch.isObstacle()== true){
            myfinch.setLED(0, 0, 255);
            myfinch.setWheelVelocities(0, 0); 
        }
        else {

            myfinch.setLED(0, 0, 0);
            random();


        }
    }

}

Solution

  • We'd need more code to answer. If your method for detecting objects always returns right away, then it is easy enough to stay in a loop until System.currentTimeMillis() shows a number more than 5000 greater than when you started. However, if your method to detect objects doesn't return until it detects something, possibly 20 seconds later, then you will need some asynchronous programming to be able to turn your LED to blue at the 5-second point.

    That approach would involve spinning off another thread to call the detect method, then waiting until either it detects something or 5 seconds elapses. You might use a BlockingQueue for the communications from one thread to the other, since that also offers a timed wait. If you don't care about detected objects after the 5 seconds, you can have the main thread interrupt the detect thread, which will let it shut down gracefully.