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

If we want to create a new function in our Blocks program, we start by pulling a block from the Functions menu:

Functions menu in Blocks showing the functions from the 2024-25 Starter Bot

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

Example 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!

New function block
New function added to our main code

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

Example of a simple code within our function

If the block is deleted this will remove the function from the "Functions" menu.

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:

Simple program for driving in a square

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:

Full code with claw opening after driving two sides

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

Function containing the code for driving and turning

Now our loop may look like this:

Using functions to drive in a square

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:

Code for controlling the robot's turn

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

Was this helpful?