• Very Useful Monster Workshop
  • Resources
  • Why micro:bit?
Imagination Coding Academy
  • Very Useful Monster Workshop
  • Resources
  • Why micro:bit?

2.1 Functions store code like memories

It is time to start making a pet monster.

Today we start exploring functions. 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.

 

Step 1 - Name it

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:

Screen Shot 2019-03-11 at 9.57.27 AM.png

Select “Make New Function” and give your function a name that will make it easy for you to remember what it does.

Step 2 - Code it

After you’ve created your function, a block will appear with your function name on it that looks like this:

functionhappy.gif

Insert your code inside the function and whenever you need to use that code, simply use the Call Function block.

Step 3 - Use your function

Using a function is as simple as using the “Call Function” block. The video 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.


Challenge

Core: Create 3 functions and use them in your robot.

Advanced: Try combining functions in interesting ways.