Skip to main content

VEX V5 - Functions

Functions and Driving

Now we will use functions to do the heavy and tedious load of drive code. Functions are chunks of code that exist outside the main function, and when called, will perform their code, and then stop. This makes driving much simpler since you can now write functions for driving forward and backward, as well as turning.

To write a function, first identify the return type of the function. This means that if you are writing a function that spits out a number or some other value, you need to specify that type in the title of the function upon declaration. For drive functions, since they do not return any kind of value, we use Void. An example of a function is below. It also takes in an integer value called seconds, which will be what we use to control the function further. This integer value is known as the parameter of the function and later on has to be specified before being able to use the function 

//void is the return type
//inside of the parenthesis is the value we will be using to control the function

void driveForward(int wt)                //this function takes a parameter Wait Time (wt) which is in miliseconds
{
  LM.spin(forward, 50,pct);
  RM.spin(forward,50,pct);
  wait(wt,msec);                          //the variable wt is a parameter of the function call
  LM.stop();
  RM.stop();
}

As seen above, the function takes a parameter called seconds. You only need to specify the type of variable in the function once, so each time you call the function it knows what to expect. A function can have many different parameters, and can take multiple at a time, or none.

Call a function in the main() using the parameters specified in the definition. Here is a drive forward function as well as two turn functions that also use time as the parameter.

int main() 
{
  // Initializing Robot Configuration. DO NOT REMOVE!
  vexcodeInit();
  driveForward(3000);          //every 1000 MSec is 1 Sec
  turnLeft(1200);              //This function does not exist so you have to create it. 
  driveForward(3000);
  turnRight(1200);

  /*
  now instead of writing dozens of lines to drive forward
  and turn back to back, you only write it once, and just
  call the function whenever you wish the robot to move like
  that.
  */

Try to make the functions for the example above. You need "Turn Left" and "Turn Right" functions or you could create just one function that does all the movements based on the speed you give it.