The conditions overrule each other.
You set the speed to 400 if the distance is >10cm. The you stop if the distance is smaller than 30.
Be aware that you might get different values when you read the sonic sesor multiple times withing a loop. Be also aware that reading sensors takes a lot of time. So better read it only once.
I would recommend:
- Code: Select all
int distance=sonic.getDistance();
while (distance >30) {
Motor.A.setSpeed(400);
Motor.B.setSpeed(400);
Motor.A.forward();
Motor.B.forward();
}
else if (distance<10) {
Motor.A.Stop();
Motor.B.Stop();
Thread.sleep(1000);
Motor.A.rotate(-90,true);
}
You may use Sound.pause(...) instead of Thread.sleep(...) because sound.pause does not throw exceptions.
Motor.A.rotate(-90,true) does not rotate the whole robot by 90 degrees. It rotates only a single wheel by 90 degrees, which is possibly not what you want because the robot will still face the wall (except when your wheel are very large).
To rotate the robot by 90 degrees you would need some calculation or use the Pilot (or DifferentialPilot) class which does that work for you. But be aware that the Pilot classes do not work properly if you set the speed value repeatedly. If you use them, you should set the speed only once outside your loop or use System.currentTimeMillis() to check the timing and ensure that you set the speed not more often that 3 times per seconds. If you set the speed too often using a Pilot class, the robot will drive with incorrect speed and bucking.
}
}