Program for NXT golf robot not looping properly This is what I made:


I will put this robot straight in line with the ball
I have to make this robot go forward and once it reaches the ball, I have to make it stop and hit the ball with the swing shown in the picture
I used ultrasonic sensor to determine if it reached the ball


It has to identify if it's a red ball or blue ball with the light sensor.
If it's a red ball the robot should hit the ball and if it's a blue ball it shouldn't hit the ball.

I used while and if statements but it doesn't seem to work properly. If I use break; then it stops the program instantly when I start it, so I didn’t use break, but if I start my code, it goes forward and stops and then continue this 
It just wouldn't go continuously

Here’s the code I wrote:

#include "NXCDefs.h"
task main() {
  SetSensorLowspeed(S2);
  ClearSensor(S2);
  SetSensorType(S1,SENSOR_TYPE_LIGHT_ACTIVE);
  SetSensorMode(S1,SENSOR_MODE_PERCENT);
  ClearSensor(S1);

  while(true) {
    OnFwd(OUT_AB,75);
    if(SensorUS(S2)&lt;=16) {
      OnFwd(OUT_AB,0);
      if(Sensor(S1)&gt;49) {
        OnFwd(OUT_C,-70);
        Wait(2000);
      }
      else {
        Wait(500);
      }
    }
  }
}
Looking at your code, there are a few things that you need to consider.

Firstly, you have a while (true) loop which will run infinitely.
The first thing you have after the loop is OnFwd(...) which will turn motors A and B on.

Together, this means that whatever you do next, when then you will run the code again, turning on motors A and B.

The next thing to be aware of is that Wait(2000) is milliseconds. 2000 milliseconds is 2 seconds, so you will only turn motors A and B off - stopping the robot - for either half a second, or 2 seconds before the loop starts again, and the robot starts moving again.

In the case where both if statements are true (presumably when it detects a red ball - but I haven't double checked either the Sensor or SensorUS commands), the robot will stop, the motor C will start, then 2 seconds later the robot will start again.

I would suggest increasing the values in the Wait statements (you could use time constants such as SEC_5), and adding a break; after the Wait(2000);