Loops

Sometimes we want to make the micro:bit do something a number of times. We could write the same code out a number of times, but this would be impossible if we wanted it to do it again and again for ever! Even if we wanted it to do something only five times, it would make a lot of code and make the program difficult to read.

A loop is a programming structure that allows the code inside it to be repeated multiple times.

We will look at 3 types of loops.


We already that if we want the mico:bit to do something forever once we have turned the mico:bit on , then we can use the Forever Event.

If you want the program to wait until you have pressed a button before repeating something forever, then we need to use a loop.

The While TRUE Do loop will help us here:

It is possible to tell the micro:bit how many times to repeat using the repeat 'n' times loop

In this example, you can see how the repeat 'n' times loop has been used to repeat the short and long flashes 3 times each as part of an improved SOS program.

This has reduced the size of the program further (17 blocks instead of 37).

Creating Loops

Watch the video below that demonstrates how to create loops

microbit - Loops.mp4

Challenge

Minot Ledge Lighthouse

Minot Ledge Lighthouse has a world famous light pattern.

It flashes its light once, then four times, then 3 times, and then repeats the sequence.

It is known as the 'I Love You' sequence (1-4-3).

Write a program that when the A button is pressed will flash the 1-4-3 sequence forever using the LED at coordinates (2,2).

Make use of loops to make you code as efficient as possible.

You should be able to write the program so that it only uses 14 blocks!!

Key Words

Loop

A programming structure that allows the code inside it to be repeated multiple times.

Efficient

To use the least amount of resources to successfully complete a task.