Chapter 4 – Visual Processing and Distance Measurement Techniques
4.3 – Functions
Functions are blocks of code that can be given a name and employed multiple times within a program to execute specific operations. They can be beneficial in streamlining code and enhancing the efficiency of debugging. You have already implemented Zumi’s functions by commanding Zumi to move forward or backward. However, did you know that you can create your own custom functions?
Step 1: What is a function?
In programming, a function is a self-contained block of code that can be assigned a name and called upon repeatedly throughout a program to perform specific tasks. Functions help summarize multiple actions into one title. For example, if you have a lot of tasks such as finishing a lot of homework, such as math, english and science homework, you can summarize it into 1 function such as “finish homework”.
Step 2: Defining a function
In the Functions Menu, we can use the first block to create a function. This function called “blink” can be used to let Zumi go forward for 1 second at 40 speed, and then blink.
Step 3: Calling a function
After creating the blink function and running the code, our function will appear in the menu as a block.
Step 4: Defining functions with parameters
Imagine if you wanted your function to perform differently based on a value or parameter? In our example previously, our blink function moves Zumi forward. But we can make her move forward for a different time each time we run the function.
Clicking on the settings button on the blink block allows us to create an input which is then accessible from the Variables Menu. We can then call the blink function which is now in the menu and also give it a input which will determine how long it travels.
Giving input of 40 to blink, which will drive Zumi forward for 40 seconds at 40 speed and then make a blinking sound.
Activity
Make a function that makes Zumi drive in a rectangle pattern using 2 parameters. These parameters will be called width and height. Set width = 2 and height = 4.
`Hint`: Will need to create a function using the function block, will need a loop block, and need to make Zumi go forwards and turn, then will later have to call the function. Also, width and height will be taken as the the number of seconds it will drive for.
Solution
Review:
Congratulations, you can start using Functions in Blockly!
Demo Video
Questions