2

I've been struggling for some time on this. I'm trying to code the robot to move when the distance is above a certain integer and stop when the distance becomes lower than the certain integer. I'm coding in Eclipse Helios. My code is below:

import lejos.nxt.Button; 
import lejos.nxt.Motor;
import lejos.nxt.SensorPort;
import lejos.nxt.UltrasonicSensor;

public class robot {
    public static void main(String[] args) {
        UltrasonicSensor us1 = new UltrasonicSensor(SensorPort.S4);

        System.out.print(us1.getDistance());

        if (us1.getDistance() >= 25);
            Motor.A.setSpeed(50);
            Motor.C.setSpeed(50);
            Motor.A.forward();
            Motor.C.forward();

        if (us1.getDistance() < 25);
            Motor.A.backward();
            Motor.C.backward();
            Button.waitForAnyPress();
    }
}
1
  • Welcome to Bricks.SE! How does this behave currently? What changes to your program have you tried?
    – jncraton
    Mar 28, 2018 at 15:59

2 Answers 2

4

It's a little unclear from your question where this is currently failing, but I do see a couple issues with your code.

1. Your if blocks are probably not doing what you expect. You should include braces to conditionally run the block following an if statement. As written, all of your code executes all of the time. This is a tricky bug to spot, as it looks correct, but isn't. You probably want to change this:

if (us1.getDistance() >= 25);
    Motor.A.setSpeed(50);
    Motor.C.setSpeed(50);
    Motor.A.forward();
    Motor.C.forward();

To this:

if (us1.getDistance() >= 25) {
    Motor.A.setSpeed(50);
    Motor.C.setSpeed(50);
    Motor.A.forward();
    Motor.C.forward();
}

2. You say that you want the motors to stop, but it looks like you are actually reversing them. You'll likely want to change this:

Motor.A.backward();
Motor.C.backward();

To this:

Motor.A.stop();
Motor.C.stop();

Your code may still need some tweaking, but hopefully those two fixes get you back on track.

1
  • 1
    I suspect the OP is more familiar with Python, hence the mistakes in the if-syntax.....
    – Phil B.
    Mar 28, 2018 at 16:58
1

Second if needs to be replaced by a loop... Very unlikely that the distance will be immediately less then 25 cm after starting the motors, you need to continuously check... And stopping the motors can then be done unconditionally (i.e. outside the while loop) Something like

while (us1.getDistance() >= 25 && !Button.ESCAPE.IsDown())
{
   Thread.sleep (1000);
}
Motor.A.stop();
Motor.C.stop();

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.