Functions on the micro:bit: the Functions palette in MakeCode

Lesson 10 of 14 · micro:bit

When the same group of blocks is repeated in several places, the program becomes long and hard to change. A function is a named group of statements: we make it once and call it as many times as needed. A function can receive data (parameters) and return a result. Functions are in the Functions palette (under Advanced).

Before you start: required prior knowledge – loops, branching.
How to learn: build every example in MakeCode and try it in the simulator (or on the device), and solve the tasks at the end on your own first; open the instructions and the solution only after that. The programs are given as blocks (description) and in JavaScript from MakeCode: in the editor click JavaScript, paste the code and go back to Blocks – you will get the same blocks.

The first function

Click Make a Function…, type a name (e.g. blink) and confirm. The block function blink appears on the workspace, and the palette gets the block call blink, which calls the function.

// function: the heart turns on and off
function blink () {
    basic.showIcon(IconNames.Heart)
    basic.pause(300)
    basic.clearScreen()
    basic.pause(300)
}

input.onButtonPressed(Button.A, function () {
    blink()     // function call
})
input.onButtonPressed(Button.B, function () {
    blink()     // the same function, another place
    blink()
})

If we want the heart to be bigger or to blink more slowly, we change only the body of the function – all calls use the new version right away.

A function with a parameter

When making a function we can add a parameter (the button Number, Text…). A parameter is a variable that gets its value when the function is called:

// how many times to blink is given when calling
function blink (times: number) {
    for (let i = 0; i < times; i++) {
        basic.showIcon(IconNames.Heart)
        basic.pause(300)
        basic.clearScreen()
        basic.pause(300)
    }
}

input.onButtonPressed(Button.A, function () {
    blink(2)    // twice
})
input.onButtonPressed(Button.B, function () {
    blink(5)    // five times
})

The same program in Python (MakeCode) – a function is made with the word def:

def blink(times: number):
    for i in range(times):
        basic.show_icon(IconNames.HEART)
        basic.pause(300)
        basic.clear_screen()
        basic.pause(300)

def on_button_pressed_a():
    blink(2)
input.on_button_pressed(Button.A, on_button_pressed_a)

A function that returns a value

The block return returns the result of the function to whoever called it. Such a function is used as a value – e.g. inside the block show number.

// returns the larger of two numbers
function larger (a: number, b: number): number {
    if (a > b) {
        return a
    }
    return b
}

input.onButtonPressed(Button.A, function () {
    let x = randint(1, 9)
    let y = randint(1, 9)
    basic.showNumber(x)
    basic.showNumber(y)
    basic.showNumber(larger(x, y))   // result of the function
})

When return is executed, the function ends immediately – that is why after the first return a the program does not reach return b.

Example: compass directions with a function

In the lesson about branching, the compass had a long sequence of conditions. If we move them into a function that returns the name of the direction, the main part of the program becomes short and readable:

function compassDirection (angle: number): string {
    if (angle < 45 || angle >= 315) {
        return "N"      // north
    } else if (angle < 135) {
        return "E"      // east
    } else if (angle < 225) {
        return "S"      // south
    }
    return "W"          // west
}

basic.forever(function () {
    basic.showString(compassDirection(input.compassHeading()))
})

The function compassDirection is easy to check even without a compass: compassDirection(90) must return "E", and compassDirection(200) must return "S".

Practice tasks

For every task there is an example, instructions and a solution. The solutions have been checked against the examples in the text.

TASK 01Difficulty: easy

Average of three numbers

Write a function average(a, b, c) that returns the average of three numbers (division by 3). When A is pressed, show the average of the numbers 4, 8 and 9.

Example

Output

7
TASK 02Difficulty: easy

Even or odd

Write a function isEven(n) that returns true if the number is even. On shake, choose a random number from 1 to 20, show it, and then show "E" for even or "O" for odd.

Example

Output

e.g. 14, then E
TASK 03Difficulty: medium

Drawing a line

Write a function line(row) that turns on all 5 LEDs in the given row. When A is pressed, the screen fills row by row from the bottom up, and when B is pressed it is cleared.

Example

Output

after A: the whole screen is lit (rows 4, 3, 2, 1, 0)
Common mistakes and tips
  • The name of a function should say what it does: blink, compassDirection, not f1.
  • A function must be called – the function block alone does nothing until you call it.
  • Parameters exist only inside the function; they cannot be used outside it.
  • A function that returns a value must have a return on every path through it.

Check your knowledge

Open the quiz

Functions

1. What are functions for?




2. How is the function blink executed?




3. What is a parameter?




4. What does larger(3, 8) from the lesson return?