GoalUse the repeat block to run blocks a chosen number of times, and work out how long the whole loop takes.
New words
loop · a group of blocks that the computer runs again and againcount-controlled loop · a loop that repeats a number of times that we chooseround · one trip through the blocks inside a loop
Explanation
Some light shows need the same blocks again and again. We could copy the blocks many times, but that makes a long, untidy program. A loop is better. In micro:bit blocks the repeat (n) times block is a count-controlled loop. We put the blocks to repeat inside it and type how many times. Every trip through the inside is one round. The total time is the time of one round times the number of rounds. Blocks below the loop run only once, after the last round has finished.
A flashing diamond. One round shows the small diamond for 500 ms and then clears the screen for 500 ms. That is 1000 ms = 1 second a round, and four rounds take 4 seconds.
A plus and X show. One round is 1000 + 1500 = 2500 ms, which is 2.5 seconds. The loop has 3 rounds, so the show takes 2.5 × 3 = 7.5 seconds. The X is still on at the end, because nothing clears it.
Blocks after the loop. The diamond pair shows twice, which takes 2 seconds. Only then does the happy face appear. It is shown once, not twice.
Class activity
Clap the loop (with family): choose a pattern, such as clap, stamp, clap, clap. Say “repeat 3 times” and do the pattern three times with a grown-up counting the rounds. Then change the number and the pattern. Make a pattern with a part before the loop and a part after it, such as one bow, then the pattern 4 times, then a spin. Can your family tell which part happened once and which part happened again and again?
Practice
1
How many times does the triangle appear, and how long does the whole program run?
The triangle appears 3 times. One round takes 2000 ms (the clear screen takes no time), so 3 rounds take 6 seconds.
2
Write the blocks for this plan: when button A is pressed, flash the big diamond 5 times. It stays on for 0.5 seconds, then the screen is off for 0.5 seconds.
on button A pressed; repeat (5) times containing show leds with the big diamond, pause (500), clear screen, pause (500).
3
What is on the display 3.7 seconds after button A is pressed? What is on the display 4.5 seconds after?
At 3.7 s the X is on, because the fourth round shows the X from 3.5 s to 4.0 s. At 4.5 s the display is blank, because the loop has ended and the clear screen has run.
4
A child wants the heart to flash 3 times. This program leaves the heart on all the time. Why?
There is no clear screen block in the loop, so the heart is never switched off. Add clear screen and a second pause inside the loop.