javaeclipsenxtlego-mindstorms

leJOS ignores my loops


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


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.