Sometimes we create some code that we find we need to use over and over again. A function is a way of creating a short cut to that chunk of code so that instead of re-writing it every time it is needed, we use or “call” the function instead. They are also convenient because if we need to change that code, the function allows us to change it on one place and it will be updated everywhere that function is called.
We will explore functions by first using them to create short cuts to different faces. This makes it easier to program the robot to have personality: happy, sad, angry, surprised, etc…
After programing the faces, think about other places where functions can come in handy.
The first thing you need to do is give your function a name. Under the Advanced section of MakeCode you’ll find a link to Function. It should look like this:
Select “Make New Function” and give your function a name that will make it easy for you to remember what it does.
After you’ve created your function, a block will appear with your function name on it that looks like this:
Insert your code inside the function and whenever you need to use that code, simply use the Call Function block.
Using a function is as simple as using the “Call Function” block. The embedded code below shows how we modify our earlier code for the face, to use a function so that when Button A is pushed, the robot smiles. (A link to the code is here.)
What should happen when Button B is pushed?
What should happen when you shake the robot? Build some more functions and use them to make the robot more interactive.
Core: Create 3 functions and use them in your robot.
Advanced: Try combining functions in interesting ways.