4

I'm using leJOS with an NXT robot. I want to scan the distances of objects from my robot. While rotating the Ultrasonic sensor from right to left, I would like to find out which object is closest to me.

Motor.A.isRotating() seemed to me as a good idea, but later I found out that leJOS hasn't implemented it yet. They are suggesting using isMoving() instead. So I tried this:

 while(!Button.ESCAPE.isDown())
   {
    Motor.A.rotateTo( 40);
    while(Motor.A.isMoving())
    {
     value = sonic.getDistance();
     LCD.clear();
     LCD.drawString("Distance: ", 0, 2);
     LCD.drawInt(value, 0, 3);
     LCD.refresh();
     Thread.sleep(100);   
    }
    Thread.sleep(100);   

    Motor.A.rotateTo( -40);
    while(Motor.A.isMoving())
     {
      value = sonic.getDistance();
      LCD.clear();
      LCD.drawString("Distance: ", 0, 2);
      LCD.drawInt(value, 0, 3);
      LCD.refresh();
      Thread.sleep(100);   
     }
      Thread.sleep(100);   
   }

I'm open to suggestions and tips! Thank you!

1 Answer 1

0

I'm not a leJOS expert, but from looking at the docs, I don't think that the rotateTo method works the way that you are expecting:

public void rotateTo(int limitAngle)

Rotate to the target angle. Do not return until the move is complete.

So here's what your code is actually doing:

Motor.A.rotateTo(40); // Rotate to 40 and return when rotation is finished
while(Motor.A.isMoving()) { // The motor won't be moving
    // Execution never gets here
}

The rotateTo method takes an optional immediateReturn parameter that allows it to return without waiting for movement to complete:

immediateReturn - if true do not wait for the move to complete

Replace your calls to rotateTo(angle) with rotateTo(angle, true), and you should be on the right track. Something like this should be more effective:

Motor.A.rotateTo(40, true); // Begin rotating to 40 and return immediately
while(Motor.A.isMoving()) { // The motor will be rotating for a time
    // Execution should loop here until the motor stops
}
4
  • Thank you very much, makes sense! I will test it tomorrow in the lab!
    – Anarkie
    May 30, 2014 at 11:30
  • When I look here lejos.org/p_technologies/nxt/nxj/api/lejos/nxt/Motor.html rotateTo() also has boolean immediate return. Will try both versions in few minutes.
    – Anarkie
    May 31, 2014 at 9:17
  • So Motor.A.rotateTo(40 , true); works but I couldn't find it without you, thanks!
    – Anarkie
    May 31, 2014 at 9:35
  • I'm glad this worked for you! I've updated the answer to include the info from your comments in case someone else runs into this problem.
    – jncraton
    May 31, 2014 at 13:02

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.