FTC Programming

Functions in Code

Explaining Java Functions

What is a function?

A function is a block of code you can feed data into or call multiple times. This is helpful, especially when you are dealing with large quantities of code.

Creating a function

Before your OpMode class ends is where we will store our functions. To create a function, all you have to do is to write the following:

    public void functionName() {
 
    }    

Anything that you put between the chttps://stempump.com/resources/course/page.php?course=FTC%20Programming&id=0 braces will run whenever this function is called, like so:

    functionName();

Giving functions parameters

Sometimes we want to make sure we can change individual variables within the function. Doing this is pretty simple. Inside the parenthesis, declare variables, but don’t initialize them.

public void driveForward(double power, double msec) {
leftMotor.setPower(power);
rightMotor.setPower(power);
sleep(msec);
}

And to call this, we just have to write:

driveForward(0.4,600);

Keep note that the first value, 0.4, gives power and the second value, 600, gives time, so this function is telling the robot to go forward at 40% for 600 milliseconds.

Returning values from functions

Say you want to receive a certain power or something from a function. You can do this like so:

public double motorPower() {
double power = 1*0.9;
return power;
}

And then, you can use this like a variable:

driveForward(motorPower(),600);

What's the point?

The whole point is to not write repetitive code and to keep your codebase to a low code count. This will ensure that everything is more organized and is easier to write. In the next lesson, we will be going over object creation, for modular code.

chevron_up