title: LeJOS NXT Programming Sonic Sensor
body: <p>I am trying to make a NXT Robot that has attached the Ultrasonic Sensor. It has to drive until the distance is 15, and then the engines have to stop. After it stops it has to turn, but it doesn't work. </p>
  
  <pre><code>import lejos.nxt.*;
  
  public class test {
      public static void main(String [] args) throws InterruptedException {
          UltrasonicSensor ultra = new UltrasonicSensor(SensorPort.S1);
          for (int i = 0; i &lt; 5; i++) {       
              try {
                  Motor.B.rotate(-1500 , true);
                  Motor.C.rotate(-1500 , true);
              } catch (Exception E){}
  
              while ( ultra.getDistance() &lt; 15 ) {
                  Motor.B.backward();
                  Motor.C.backward();
              }
  
              LCD.clear();
              LCD.drawString("Distance : "+ultra.getDistance(), 0, 0);
          } 
  
          Button.waitForAnyPress();
      }
  }
  </code></pre>
  
  <p>My old code, which also didn't work:</p>
  
  <pre><code>import lejos.nxt.*;
  
  public class test {
  
  public static void main(String [] args) throws InterruptedException {
      UltrasonicSensor ultra = new UltrasonicSensor(SensorPort.S1);
      try {
          Motor.B.rotate(-720);
          Motor.C.rotate(-720);
  
           } catch (Exception E){}
  
      for (int i = 0; i &lt; 5; i++)
      {
      LCD.drawString("Distance : "+ultra.getDistance(), 0, i);
                Thread.sleep(2000);
           int maxDistance = ultra.getDistance();
           if (maxDistance &lt; 15){
               Motor.B.stop();
               Motor.C.stop();
           }
      }
      Button.waitForAnyPress();
  }
  }
  </code></pre>