Exploring Functions

What is a Function?

Functions act similar to a variable in that we are using one thing to represent another. However, where a variable typically is used in place of something short, such as a number, a function can take the place of several lines of code.

This can be incredibly useful if there is a section of code we know will be repeated or to break apart our code into chunks for easy editing.

Creating a new Function in Blocks

Next we will replace "do something" with an appropriate name. Maybe in this case we are adding a new function for climbing:

Once our function is named it will appear in the "Functions" menu to be added to the main loop or wherever we need it within our code!

All that's left is to add whatever code we'd like to be within this function:

When to use Functions - Example

This example was originally created as part of the 2024-25 FTC Starter Bot program, but can be followed on a different robot!

After configuring, create a new OpMode to begin. Ours is named FunctionsDemo.

Let's say we are working on an autonomous code where we want our robot to drive roughly in a square. Remember that autonomous means this code will move the robot on its own when play is pressed:

Next, let's say we need the robot to do something between one of the turns, such as move its arm or open a servo's claw. There's a couple of ways we could approach this without functions:

Already our code is getting a little long so let's move our side motion and turn into a function:

Now our loop may look like this:

When we test our code we may notice our robot isn't exactly driving in a square shape. Thankfully with our function in place we only need to change the needed value in one place:

This change to the function will be reflected anywhere DRIVE_AND_TURN used.

Give it a try by changing the right motor's power or the timer to refine your square!

Last updated