NXT golf bot

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() {

  while(true) {
    if(SensorUS(S2)<=16) {
      if(Sensor(S1)>49) {
      else {

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);

New contributor
Holmez is a new contributor to this site. Take care in asking for clarification, commenting, and answering. Check out our Code of Conduct.
  • Thank you for your answer. Bless You!! – HelpmePlz Nov 8 at 18:11

Your Answer


By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.