Question

I just installeds leJOS for my NXT 1.0 and it worked just fine. I am using Eclipse to write the code and uploade it to the block. The only problem I have is that the block completely ignores my code:

import lejos.nxt.*;

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

    TouchSensor touch = new TouchSensor(SensorPort.S1);
    SoundSensor sound = new SoundSensor(SensorPort.S3);

    Motor.A.setSpeed(1000);
    Motor.B.setSpeed(1000);
    Motor.A.forward();
    Motor.B.forward();

    /*try{
    Thread.sleep(10000);
    } catch (Exception e) {}
    */

    if (touch.isPressed()) {
        Motor.A.flt();
        Motor.B.flt();
        LCD.drawString("Done", 3, 4);
        NXT.shutDown();

    } else {
        Motor.A.forward();
        Motor.B.forward();
    }

    Button.waitForPress();

I put the Button.waitForPress(); in there so I could check what the program actually does. If I run it in this configuration It moves forward and keeps going until I press a button. If I uncomment the Thread.sleep() command the robot goes for the amount of time I assigned to wait for and than stops, completely ignoring in both cases that I want it to watch for the touch sensor to be pressed. All the sample programs work but I did not find a loop in them so what I think is that there is a problem with my loop. Is there anyone who can help?? Thanks already

Was it helpful?

Solution

I'd answer as a comment, but I don't think i can do that and make it readable..

My guess is that touch.isPressed() is returning true without the sensor actually being pressed. The sensors are not overly reliable and it is possible that it isn't quite in an initialized state.

I'd change the code to look like this for now, just to debug the issue:

Motor.A.setSpeed(1000);
Motor.B.setSpeed(1000);
Motor.A.forward();
Motor.B.forward();

if(touch.isPressed()) 
{
   LCD.drawString("Pressed", 3, 4);
}
else
{
   LCD.drawString("NOT Pressed", 3, 4);
}

Button.waitForAnyPress();

// rest of your code

That way you can be 100% sure what isPressed is returning.

OTHER TIPS

You should use a while loop and then put your if-else statements inside that like - while (true) { write code here. }

but in the above case, your program will run forever, will not stop. so, better if you give a condition in your while loop. if any doubt, i can tell you again

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top