Subroutines

Subroutines

Sometimes we will want a program to do the same thing in different places in our program. Rather than write the same bit of code again and again, we can group a section of code together in a subroutine and give it a name. We then can call the name of the subroutine and it will run the code inside it.

A good example would be with our SOS program.


The SOS program used this code this code to do a short flash

The program used this code to do a long flash.

It then used the same code again and again to program the correct sequence.

Although the code works, the problem is that it is very long and very difficult to follow. Another problem would be if we wanted to change the length of the short flash to 250ms, we would need to change the code it 6 different places.

The solution is to use a subroutine or as MakerCode calls them a function.

The function block is a programming structure that can be given a unique name.

How to make a function

Under the 'Advanced' options, choose 'Functions'.

Click the 'Make a Function...' button.

Give the function a meaningful name that says what the subroutine will do.

Add the code you want the subroutine to perform.

There is now a new block in the Functions menu that will call our subroutine!

You can use that new block in your actual program.

The program below is the solution for the SOS program but using subroutines.

Notice that the program is much shorter (it uses 20 blocks instead of 37).

It is much easier to read as well.

If you now want to change how long the shot flash lasts, you only need to change the code in the subroutine.

Press A to run the original code.

Press B to run the code that uses subroutines.

The program could be improved further by creating a subroutine for each letter; one for S and one for O.

Making Subroutines (Functions)

Watch the video below to see how to make a subroutine (function)

microbit - subroutines.mp4

Challenge

Morse Code

Write a program that will spell out your name in Morse Code when you press the A button.

  • Create a subroutine for a short flash

  • Create a subroutine for a long flash

  • Create a subroutine for each different letter of your name

    • for each letter, call the correct sequence of short and long flashes

  • Using the On button pressed event, call the correct sequence of letters to spell out your name.

The Morse Code Table

A dot represents a short flash.
A dash represents a long flash.

The subroutine for the letter Q

Key Words

Subroutine

A small section of code that completes a task and can be re-used in a program by calling it.

Function

A function is a type of subroutine. It most programming languages a function will return a value.