Search code examples
javawhile-looprobotics

Robot Obstacle Recording/Avoiding


I'm trying to make this robot go in random directions until it reaches an obstacle. Then it should record that obstacle (Obstacle = 1,2,3 etc) and switch direction. This should go on until the timer expires.

public static void main(String args[]) throws Exception{

    Robot therobot = new Robot();

    int x = 10000;
    int obstacles = 0;
    Random rand = new Random();
    int r1 = rand.nextInt(255) + 1;
    int r2 = rand.nextInt(255) + 1;

    therobot.setWheelVelocities(100,100);
    long before = System.currentTimeMillis();

    while (System.currentTimeMillis() - before < x){
        Thread.sleep(x);
        if( therobot.isObstacle() ==true || therobot.isTapped() == true)
        {
            r1 = rand.nextInt(255) - 255;
            r2 = rand.nextInt(255) - 255;
            obstacles = obstacles++;

            therobot.setWheelVelocities(r1, r2);
        }
    }
    System.out.println(obstacles);

    therobot.stopWheels();
    therobot.quit();
}

But this doesn't seem to work. It just goes until the timer expires but it won't stop or record anything.

What am I missing ?


Solution

  • Having

    int x = 10000;
    long before = System.currentTimeMillis();
    while (System.currentTimeMillis() - before < x){
        Thread.sleep(x);
        // Processing
    }
    

    The first iteration of while loop takes entire time duration of 10 seconds because of Thread.sleep(10000).

    Sleep amount should be significantly lesser than total duration.