Beginner Tutorial - Part 3: Let's see something turn

From NXT++

Jump to: navigation, search

OK. So lets recap. We've set up your compiler for NXT++ and compiled your first program, but you still haven't done anything with the NXT yet. Let's start off by making something turn! Motors are very easy to control in a simple robot, but they can get a lot more complicated in an advanced one. Lets begin by making Tribot go forward for two seconds. If you don't have Tribot built, you can always optimize the program for your robot. Here are the functions you'll need to know:

  • The function for turning a motor on, SetForward(). You can look at how this function is used in the API reference.
  • The nifty little function that comes with NXT++, Wait().
  • The function for stopping a motor, Stop()

You also need to know about namespaces. Namespaces are basically categories that you can put your functions in. They help you organize your code and make it look neater. Let's begin by example: to turn a motor on, you would use SetForward(), but it would actually be written NXT::Motor::SetForward(). The API reference is the easiest way to find out the namespace a function is in.

An example program

Now let's see how you implement these functions in the program you made in Part 2. First of all, since we have 2 motors (OUT_A and OUT_C) we need to set both of them to 50% power:

NXT::Motor::SetForward(&comm, OUT_A, 50);
NXT::Motor::SetForward(&comm OUT_C, 50);

Next, we wait for two seconds (2000 miliseconds):

Wait(2000);

Finally, we turn the motors off:

NXT::Motor::Stop(&comm, OUT_A, false);
NXT::Motor::Stop(&comm, OUT_C, false);

If we add all that code into the main body of the program we made in the previous tutorial, we get this:

#include "NXT++.h"
 
int main()
{
    Comm::NXTComm comm;
    if(NXT::Open(&comm)) //initialize the NXT and continue if it succeeds
    {
        NXT::Motor::SetForward(&comm, OUT_A, 50); //turn both motors on 50% power
        NXT::Motor::SetForward(&comm, OUT_C, 50);
        Wait(2000); //wait 2 seconds
        NXT::Motor::Stop(&comm, OUT_A, false); //stop both motors with no braking
        NXT::Motor::Stop(&comm, OUT_C, false);
        NXT::Close(&comm); //close the NXT
    }
    return 0;
}

Compile, turn on the NXT, and run the program. Be sure to lift the NXT off your desk if you are using USB so it doesn't run off the table! :)

On to Part 4: Interacting with the environment

Personal tools