Step 3

Creating a function


Let’s start out with our first big problem, making sure we don’t drive off the map.

To solve this, we can make something called a function. Think of a function as a sort of “shortcut” for code. When we define a function, we tell it what code blocks to use when we call/use it in other code. If this sounds confusing now, it should make more sense as we start using them.

In this program, functions are called “custom blocks”. To create one, go into the “My Blocks” section. Name this function “driveUntilRed”.

Completing and testing the function


Now that we have made our function, let’s define it.

In this function we will make our robot drive forward until its “DownEye” sensor sees the color red. Once it does, the function will end, pretty simple, but very powerful.

Next, test out the function to see if it works. We also set the speed of our robot to be 60% for this project. If we move too fast, we run a risk of detecting the color red too late and falling off the map, so 60% works well here.

Notice how we already knocked down 1 of 5 structures! It’s not in the order we wanted but it’s progress.

Now that we have this, see if you can complete the code for the rest of the project. It’s actually not that hard now that we have the function! Hint: We can knock down the middle structure, how do we modify our code to knock the right one down instead? How about the left one? Repeat this process until all the structures are knocked down!

When you are ready to see the solution, move on to the next page.