0% found this document useful (0 votes)
160 views

Micro Bit Lesson 456

This lesson introduces conditional statements using the "If...then" and "If...then...else" logic blocks. Students will understand conditional statements, practice using logic blocks so different conditions yield specified outcomes, and collaborate to create a board game that uses conditionals. Activities include acting out conditionals, coding a rock paper scissors game on micro:bit, and creating an original board game where micro:bit is central and conditionals are used.

Uploaded by

jorge diaz
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
160 views

Micro Bit Lesson 456

This lesson introduces conditional statements using the "If...then" and "If...then...else" logic blocks. Students will understand conditional statements, practice using logic blocks so different conditions yield specified outcomes, and collaborate to create a board game that uses conditionals. Activities include acting out conditionals, coding a rock paper scissors game on micro:bit, and creating an original board game where micro:bit is central and conditionals are used.

Uploaded by

jorge diaz
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 48

An Introduction to

Computer Science with 1 -

BBC micro:bit
Lesson 4-6
Developed by Microsoft
Conditional Statements

This lesson introduces the Logic blocks such as 'If...then' and 'If...then...else'.
Students practice skills of creativity, problem-solving, and collaboration.

Lesson Objectives

• Understand what conditional statements are, and why and when to use them in a program.
• L L 'I ' 'I … '.
• Practice using the Logic blocks so different conditions yield specified outcomes.
• Demonstrate understanding and apply skill by collaborating with classmates to create a
game that uses a micro:bit and a program that correctly and effectively uses conditionals.

Lesson Plan Structure


• Introduction: Conditionals in daily life
• Unplugged Activity: Red if, Green then
• Micro:bit Activity: Rock Paper Scissors
• Project: Board Game
• Assessment: Rubric for board game project
• Standards: Listed

Introduction
Computer programs are instructions telling the computer how to process input and deliver
output.
An important part of programming is telling the computer WHEN to perform a certain task.
F , ‘ ’ Conditionals get their name because a certain
Condition or Rule has to be met.

Students are all already familiar with the concept of conditionals in their daily lives!

Have they ever had their parents say..?


• “I , ”
• “I , ”
• “I , , ”

These are all conditionals! Conditionals follow the format of IF this, THEN that.
IF (condition is met), THEN (action performed)

Have the students share a few conditionals from their own lives with the class or within small
groups.

Note: For older students, you can have them add the ELSE portion of a conditional.
IF (condition is met), THEN (action performed), ELSE (different action performed)

Example:
• IF it is snowing, THEN wear boots, ELSE wear shoes.

The ELSE portion makes sure that a different action is performed in either case. Without the ELSE

04.Conditionals Page 62
The ELSE portion makes sure that a different action is performed in either case. Without the ELSE
action, your students might be barefoot!

Tell the students that they will be acting out some conditionals as though the whole class is a
computer program for a game. Each student will perform a described action if the indicated
condition is met.

Note: This activity can be done as a whole class or in smaller groups or as a pencil and paper
activity.

04.Conditionals Page 63
Unplugged: Red Light Green Light

Objective
To reinforce the programming of basic conditionals by having students experience conditionals
through acting them out in real life.

Activity Overview
Students will line up at one end of the classroom with the goal of reaching the other side of the
classroom. The teacher, and then the students themselves will call out conditionals and all the
students will advance or not depending on the specific conditional statement.

N ‘ ’
running of the program.

Materials
• Pencils and lined paper (if doing this activity seated). Students can advance across the
paper instead of the room with one inch line equal to one step.

Process
• Have the students line up at one side of the room.
• Explain the rules:
○ The object of the game is to get across the room first.
○ F 'I ' I ‘ ’ ,
‘ ’ I ‘ ’ ,
nothing.
○ F 'I ' , , ‘ ’
may apply to you.

Example conditional statements


• If you are wearing something green, then take a step forward.
• I ‘ ’ ,
• If you are wearing sneakers, then take a step forward, else take 2 steps forward.
• If your birthday is this month, then take a giant hop forward.
The conditionals you use will depend on your individual class.

After the students get the idea of the game, allow them to make up and call out conditionals
(that meet teacher approval).

They will need to be observant, as a conditional that moves them forward, will also move their
competition forward!

04.Conditionals Page 64
competition forward!

Tips
• SAFETY FIRST! Students, especially younger ones, can get quite silly with this and while it is
meant to be fun and even funny, safety first!
• Student conditionals need to apply to at least two people in the class.

Reflections
H ? W ‘ - ’? D
or fail to correctly carry out the THEN or ELSE action? Were there some conditions that could be
evaluated as something other than True or False (maybe, sometimes)?

Extensions/Variations
• Add AND, OR, AND/OR statements to the conditionals.
I ND , …
• IF’
I , … ,
steps forward.
• Let students create their own conditionals for future program runs with the class. (A very
popular activity, though all conditionals should be run by the teacher first for approval.)
• Relate this activity to a system and have the students create the conditionals that would
end in a product of some kind or the completion of some task, like writing a sentence or
setting a table or constructing a simple structure.

04.Conditionals Page 65
Activity: Rock Paper Scissors

For this activity, each student will need a micro:bit.


Everyone will create the same program, the classic rock paper scissor game.

Introduce activity
• Have students recall the classic rock paper scissors game.
• What are the rules of the game? What are the conditionals?
• Example:
If Player A gets rock, and Player B gets scissors, Then Player A wins.
• Have students write the pseudocode for how to play the game on the micro:bit.
Example pseudocode:
On button A press: choose random number from 0-2
If random number = 0, then display rock icon,
Else if random number = 1, then display paper icon,
Else display scissors icon.
• , ’
check to see if random number = 2. So we just use an else.

Micro:bit
• Working from the specifications, have students work in pairs to try to code a Rock Paper
Scissors game on their own.
• If students get stuck, there is a tutorial at https://pxt.microbit.org/projects/rock-paper-
scissors (steps 1 through 4), that leads students step-by-step through the process of
coding a working rock paper scissor game for their micro:bit.
• Let them play the game against their program.

Ideas for Mods


○ Add a way to keep score: Steps 5 through 7 in the tutorial
○ ‘R
Lz ’, 8

rock-paper-scissors

04.Conditionals Page 66
04.Conditionals Page 67
Project: Board Game

This is an assignment for students to create a board game. It should take two to three class periods. If your school has a makerspace or an
art classroom where students can access materials such as cardboard, poster paints, or markers, you might schedule your classes to work
there.

O , ’ I , give them some


time to give and gather feedback, then revise their games accordingly.

Introduction
Many board games use an electronic toy to signal moves, or provide clues. There are some funny examples online if you search for
“ ” H

Dark Tower (featuring Orson Welles): This is an example of a circular board game in which the pieces start on the edges and move in toward
the middle.

Electronic Dream Phone Board Game Commercial - 1992: This board game is really a logic puzzle. There are printed clues that illustrate
relationships and the phone provides clues that help you to narrow down possibilities by a process of elimination.

Stop Thief Electronic Board Game commercial 1979: This board game uses a device to give audio clues that help you to figure out what to
I’

Assignment
Students should work in pairs to create an original board game project in which micro:bit is a central feature, and the rules of their board
game should use Conditionals.

Students will need to work together to come up with:


• A set of written rules (how to play)
• A game board
• A program for the micro:bit
• Photo documentation of the different game pieces, cards, or other components of the game with the micro:bit included as well as a
screenshot of your micro:bit code. Each photo must have a caption that describes what the photo is documenting.
• R ’ ’
brainstorming ideas, through construction, programming, and beta testing.

The micro:bit needs to work in conjunction with the game board and/or game pieces and should be a central feature of the game. Ideally, it
should be more than a simple substitute for a six-sided die.

The Micro:bit might:


• Simulate the results of a battle between two pieces
• Randomly point in a different direction of travel
• Generate a result based on its current incline
• Point randomly at players and kill them
• Display a dynamic score
• ... let your imaginations run wild!

Ideally, students should be writing their own versions of Micro:bit programs to do something original.
Here is one simple program to discuss and use as an example:

Battle Game Pieces


In this example, pieces start out at full strength and lose points based on random events on the board. When two pieces meet on the same
space, they battle.
• Press A to enter the strength of piece A.
• Then press B to enter the strength of piece B.
• Shake the Micro:bit to determine the winner of the battle, which is proportionately random to the strength of each piece.

04.Conditionals Page 68
let p2 = 0
let p1 = 0
input.onButtonPressed(Button.A, () => {
p1 += 1
basic.showNumber(p1)
})
input.onButtonPressed(Button.B, () => {
p2 += 1
basic.showNumber(p2)
})
input.onGesture(Gesture.Shake, () => {
if (Math.random(p1 + p2 - 1 + 1) + 1 <= p1) {
basic.showString("A")
} else {
basic.showString("B")
}
})

BattleGame

04.Conditionals Page 69
Beta Testing
G ’
• Have each pair of students set up their own project at their table.
• Leave a clipboard or a laptop on the table for taking notes.
• Rotate the students through each project, moving clockwise around the room:
○ Play the game (5 min)
○ Fill out a survey form (5 min)

Sample Survey questions


• How easy was it to figure out what to do?
• What is something about this project that works really well?
• What is something that would make this project even better?
• Any other comments or suggestions?

Many online survey tools will allow you to sort the comments by project and share them with project creators so they can make
improvements based on that feedback.

Reflection
Have students write a reflection of about 150–300 words, addressing the following points:
• Explain how you decided, as a pair, on your particular board game idea.
• What was something that was surprising to you about the process of creating this game?
• Describe a difficult point in the process of designing this game, and explain how you resolved it.
• What feedback did your beta testers give you? How did that help you improve your game? What were the Conditionals that you used
as part of your game rules?

Board Game Example


Space Race by K. and S.
• How to win: Starting from Earth, your goal is to progress to Mars. The first person to reach Mars is the winner.
• Rules:
○ Shake the microbit to randomize how far you get to advance
○ If you land on a pink square, press “B” on the Micro:bit until your previous roll number appears. Then press A and B at the same
time to see whether or not you move based upon the number on the square
○ Up to four players

04.Conditionals Page 70
Finished Game

Micro:bit Holder

04.Conditionals Page 71
Game Pieces

let yes_or_no = 0
let current_roll = 0
let previous_roll = 0
input.onButtonPressed(Button.AB, () => {
previous_roll = 0
if (4 <= previous_roll) {
yes_or_no = Math.random(8)
}
if (4 > previous_roll) {

04.Conditionals Page 72
if (4 > previous_roll) {
yes_or_no = Math.random(5)
}
if (2 < yes_or_no) {
basic.showString("YES")
basic.clearScreen()
} else {
basic.showString("NO")
basic.clearScreen()
}
})
input.onGesture(Gesture.Shake, () => {
current_roll = Math.random(6)
basic.showNumber(current_roll + 1)
basic.pause(5000)
basic.clearScreen()
})
input.onButtonPressed(Button.B, () => {
previous_roll += 1
basic.showNumber(previous_roll)
})
input.onButtonPressed(Button.A, () => {
previous_roll += -1
basic.showNumber(previous_roll)
})
basic.showString("SPACE RACE")
previous_roll = 0

SpaceRace

Assessment

4 3 2 1
Rules All game rules are clear and A game rule is missing or More than one game rule Most of the game rules are
complete not complete or not clear is missing or not complete missing or it is not clear
or not clear what the rules are.
Game board Game board is: Game board meets only 3 Game board meets only 2 Game board meets only 1

04.Conditionals Page 73
Game board Game board is: Game board meets only 3 Game board meets only 2 Game board meets only 1
• Complete of the conditions listed for of the conditions listed for of the conditions listed for a
• Neat a score of 4. a score of 4. score of 4.
• Fits with the theme of the game
• Micro:bit is a central part of the
game
Micro:bit Micro:bit program: Micro:bit program lacks 1 Micro:bit program lacks 2 Micro:bit program lacks 3 of
program • Uses the Micro:bit in a way that is of the required elements of the required elements the required elements
integral to the game
• Uses conditionals correctly
• Compiles and runs as intended
• JavaScript includes comments in
code
Photo Complete photo documentation A photo is missing or of Multiple photos and/or Most photos and/or
documentation that includes photos of game poor quality or a caption is captions missing or of captions missing or of poor
board and code and captions. missing. poor quality. quality.
Collaboration Reflection piece includes: Reflection piece lacks 1 of Reflection piece lacks 2 of Reflection piece
reflection • Brainstorming ideas the required elements. the required elements. lacks 3 of the required
• Construction elements.
• Programming
• Beta testing

04.Conditionals Page 74
Standards

CSTA K-12 Computer Science Standards

• CL.L2-03 Collaborate with peers, experts, and others using collaborative practices such as
pair programming, working in project teams, and participating in group active learning
activities.

• CL.L2-04 Exhibit dispositions necessary for collaboration: providing useful feedback,


integrating feedback, understanding and accepting multiple perspectives, socialization.

• CL.L3A-01 Work in a team to design and develop a software artifact.

• K-12 Computer Science Framework Core concept: Control Structures

04.Conditionals Page 75
Iteration

Iteration & Looping


This lesson introduces the concept of looping and iteration. Presents the 'While' block as a
combination of an iteration and a conditional statement.

Lesson Objectives

• Understand the value of iteration in programming
• Understand looping as a form of iteration
• L L ‘ ’, ‘ ’, ‘ ’
• Apply the above knowledge and skills to create a unique program that uses iteration and
looping as an integral part of the program

Lesson Plan Structure


• Introduction: Lather. Rinse. Repeat.
• Unplugged Activity: Walk a Square pseudocode
• Micro:bit Activities: Code a Sprite to Walk a Square, Travelling Light, Micro:bit Alarm!
• Project: Get Loopy!
• Project Mods: Use servo motors to add a motion element to the project
• Assessment: Rubric
• Standards: Listed

Introduction
In computer programming, iteration is the repetition of a sequence of code. A loop is a form of
iteration. A loop repeats code until a certain condition is met.

Questions for the students:


• Do you use shampoo to wash your hair? Most will say ‘Yes’.
• Have you ever read the instructions on a bottle of shampoo? Most will say ‘No’.

Most of us have never read the instructions on a bottle of shampoo, because we already know
how to use shampoo.

What algorithm could you write for shampooing your hair?


Example:
1) Wet hair.
2) Apply shampoo to wet hair
3) Scrub shampoo into hair
4) Rinse shampoo out of hair

If you did read the instructions on a bottle of shampoo, you may read similar instructions as the
‘R ’
How does this one extra step affect the algorithm?

05.Iteration Page 76
I , ‘ ’
I ‘ ’ ‘ ’
no condition that ends the looping.

DBwebsolutions.com
‘R R ’
What other common activities involve repetitive actions? Examples: Singing (choruses repeat),
dancing, school cheers, walking and running, exercise routines...

Optional
‘L ,R ,R ’

Lather, Rinse, Repeat: Hygiene Tip or Marketing Ploy


By Lauren Goldstein
October 11, 1999
http://archive.fortune.com/magazines/fortune/fortune_archive/1999/10/11/267035/index.htm
(FORTUNE Magazine) – In Benjamin Cheever's novel The Plagiarist, a marketing executive
becomes an industry legend by adding one word to shampoo bottles: REPEAT. He doubles

05.Iteration Page 77
becomes an industry legend by adding one word to shampoo bottles: REPEAT. He doubles
shampoo sales overnight.

This bit of fiction reflects a small yet significant eddy of U.S. consumer angst: If we REPEAT, are
we or are we not playing into the hands of some marketing scheme? It turns out that in real life
there's a reason you should repeat, or at least there used to be. In the 1950s, when shampoos
began to be mass-marketed, we didn't wash our hair all that often--once or twice a week, as
opposed to five times a week as most of us do now. Also, we used a lot more goop in our hair.
It was the age of Brylcream and antimacassars, remember. Paul Wallace, the director of hair-
care research and development for Clairol, says that when cleaning agents in shampoo came up
against that amount of oil and goop, "it depressed the lather." A second application was
needed to get the suds that consumers expected. Lots of suds mean that hair is already clean.
Maybe too clean (there's no oil to break through), but consumers like it.

FORTUNE asked Frederic Fekkai, the noted and notably expensive New York City hairdresser,
what he thought about the double lather. He says, "Yesterday I put oil on my hair for a different
look and went to a restaurant where the smoke was horrible. This morning I realized I had to do
two shampoos."

At any rate, Wallace says advances in shampoo technology mean that only one application of,
for instance, Clairol's Herbal Essences is sufficient to break through the oiliest hair. The
company has stricken the use of both REPEAT and REPEAT IF DESIRED from all Clairol products.
Yet a lot of brands, like Suave by Unilever and L'Oreal, still say REPEAT. Others, like Unilever's
Finesse and Revlon's Flex, opt for the less imperative REPEAT IF DESIRED. Procter & Gamble
uses REPEAT IF NECESSARY on Pantene.

Getting consumers to wash twice can, of course, increase sales--in ways one might not imagine.
Double sudsing leads to dry hair, Fekkai points out, and that means more beauty products!
"When you do two shampoos, even if you don't usually use a conditioner, you have to use a
little," he says. "The conditioner becomes very important." REPEAT. FOLLOW WITH
CONDITIONER. Words Cheever's marketer could have retired on.
--Lauren Goldstein

From Wikipedia (https://en.wikipedia.org/wiki/Lather,_rinse,_repeat):


Lather, rinse, repeat (sometimes wash, rinse, repeat) is an idiom roughly quoting the
instructions found on many brands of shampoo. It is also used as a humorous way of pointing
out that such instructions if taken literally would result in an endless loop of repeating the same
steps, at least until one runs out of shampoo. It is also a sarcastic metaphor for following
instructions or procedures slavishly without critical thought.

05.Iteration Page 78
Unplugged: Walk a Square

Objective
To reinforce the concept of iteration by having students act out the repeated steps of an
algorithm in real life.

Overview
Students will give the teacher instructions to do a simple activity, then look for places where
using iteration could shorten their code and make it more efficient.

Process
• Place a chair in the front of the room.
• Stand at the back right side of the chair facing the students.
• Ask the students what instructions they could give you that when followed would lead you
to walk around the chair, ending up just as you started. You may want to demonstrate
what this would look like by walking around the chair.
• Tell the students you can only process one instruction at a time, so their algorithm needs
to be step-by-step.
• As students suggest instructions write them on the board or wherever everyone can see
them.
Their pseudocode will probably end up looking something like this:
1) Step forward
2) Turn left
3) Step forward
4) Turn left
5) Step forward
6) Turn left
7) Step forward
8) Turn left

• Go ahead and follow their algorithm to prove that it works.


B ’ !

05.Iteration Page 79
B ’ !
just three lines of code. If they have not noticed already, have students look for places
where the code repeats.

• Tell them that whenever you have code that repeats, you have an opportunity to use a
loop to simplify your code.
• Prompts:
○ What lines are repeated? 1) Step forward. 2) Turn left.
○ How many times are they repeated? Four
○ So how could we rewrite this code? Students will suggest a version of the following:
Repeat 4 times:
1) Step forward
2) Turn left

• Go ahead and follow their revised algorithm to prove that it works.

There! They have just rewritten eight lines of code as three lines of code, by using a loop.
‘ ’
of times until a condition is met. The condition in this algorithm is that the code in the loop is
repeated 4 times. Once this condition is met, the program exits the loop.

This is a great opportunity to have the students think of the benefits of having fewer lines of
code. Some possible reasons: Less typing, saves time, fewer chances of making a mistake, easier to
read the code, fewer lines of code to debug...

Notes
• Depending on the particular class, you can make this exercise more challenging, by
requiring the students to be more specific in their instructions.
For example: Step forward 14 inches (you can have students actually measure the exact
, 9 …

05.Iteration Page 80
Activity: Loops Demos

Microsoft MakeCode has three different loop blocks:


• 'Repeat' block
• 'While' block
• 'For' block

To start, the students can code the same algorithm they created in the unplugged activity using
a loop.

‘Repeat’ block
Code a Sprite to walk a square. Have students click on the Loops category in the Toolbox, and
look at the three choices available.

‘ ’ !H
W ’ parameter.

A parameter is a type of variable used as input to a function or routine. In this case, the
parameter tells the repeat block how many times we want the code within the block to repeat.

F , ’

To create a sprite that will walk a square:

• Click on the Advanced category in the Toolbox. This will open up a more advanced menu
of blocks.
• G , ‘ ’

05.Iteration Page 81
• W ’ G R ‘W q ’
pseudocode, see if the students can find the blocks they need for moving their sprite and
turning their sprite.
• D ‘ ’ ‘ ’
• They now have these blocks in their coding workspace.
• F , ‘ ’

Time to fix those default parameter values!


• We want our sprite to start in the top left corner of the micro:bit screen, so change the
parameters for both x and y to zero.
• To make the sprite move from one side of the screen to the other (as though walking
around a chair), change the move by parameter to 4.
• q , ‘ ’ 90. For
now, it's OK to leave the sprite turning right instead of left as we did in our pseudocode.

Your blocks now look like this:

05.Iteration Page 82
N ’
event handlers.

• On start, we want the sprite to appear. To make this happen, go to the Variables menu and
‘ ’
• ‘ ’ ‘ ’
• ‘ ’ ‘ ’

let item: game.LedSprite = null


item = game.createSprite(0, 0)

You should now see the sprite appear in the top left of the microbit simulator.

• , ‘ ’
the Input menu.
• ‘ ’ ‘ ’
• ‘ ’ ‘ ’
• ‘ ’ ‘ ’ ‘ ’

input.onButtonPressed(Button.A, () => {
for (let i = 0; i < 4; i++) {
item.move(4)
item.turn(Direction.Right, 90)
}

05.Iteration Page 83
}
})

Go ahead and run the program. Make the sprite move by pressing button A.

What happened? Did you see the sprite move? No?

Slo-Mo
A helpful feature of Microsoft MakeCode is "Slo-Mo", or slow-motion mode.
• Click on the snail icon under the micro:bit simulator.
This will slow down the execution (running) of the program, and highlight parts of your code so
you can see step-by-step, which line of code is being processed.

Now run your program several more times. Do you see the different lines of your code
highlighted as the program runs? Do you see the sprite move?

Slo-Mo in Blocks

Slo-Mo in JavaScript

So, the code is running and the sprite is moving! Sometimes we forget just how fast computers
‘ ’ ,
right after each time the sprite moves. This will give our human eyes a chance to see it move.

05.Iteration Page 84
right after each time the sprite moves. This will give our human eyes a chance to see it move.

• Click the snail icon again to turn off Slo-Mo.


• F B , ‘ ’
‘ ’ ‘ ’

Your final program should look like this:

let item: game.LedSprite = null


input.onButtonPressed(Button.A, () => {
for (let i = 0; i < 4; i++) {
item.move(4)
item.turn(Direction.Right, 90)
basic.pause(100)
}
})
item = game.createSprite(0, 0)

WalkaSquare

05.Iteration Page 85
Run your program again. Now we can see the sprite move. It still moves pretty quickly, but at
least we can see it move.

If there is time, let the students experiment with changing the parameters to see how these
changes affect their program.

We just used the first of the 3 different types of Loop blocks available to us. What about the
,‘ ’ ‘ ’?

‘For’ block: Traveling Light


‘ ’
W ?L ’
at an example.

L ’ ,

Our pseudocode for the first row might look like this:
Turn led x:0, y:0 on
Pause
Turn led x:0, y:0 off
Pause
Turn led x:1, y:0 on
Pause
Turn led x:1, y:0 off
Pause
Turn led x:2, y:0 on
Pause
Turn led x:2, y:0 off

05.Iteration Page 86
Turn led x:2, y:0 off
Pause
Turn led x:3, y:0 on
Pause
Turn led x:3, y:0 off
Pause
Turn led x:4, y:0 on
Pause
Turn led x:4, y:0 off

’ ,

• What is the only variable that is changing in this pseudocode? The value of the x
coordinate.
• How much is the value of the x coordinate changing each time? The value of the x
coordinate is changing by 1 each time.
• What is the range of values for the x coordinate? The range of values for the x coordinate
is 0 through 4.

N ’ !

• F L , ‘ ’
• ’ , , xindex.
• W ’ F L ,
a 'plot' block and an 'unplot' block to the coding workspace.
• F B , ‘ ’
• ‘ ’ ‘ ’ , ‘ ’ , ‘ ’
block, the second 'pause' block.
• ‘ ’

L ’

• ‘ ’ ‘ ’ ‘ ’
• Change the value of the x coordinates in the plot and unplot blocks to this same variable.

05.Iteration Page 87
let index = 0
basic.forever(() => {
for (let xindex = 0; xindex <= 4; xindex++) {
led.plot(xindex, 0)
basic.pause(100)
led.unplot(xindex, 0)
basic.pause(100)
}
})

We can use the default values for the rest of the parameters.

You should now see a light moving from left to right along the top row of the micro:bit
simulator.

To make our pattern continue through all the leds, we can change the value of the y coordinate
as well.

To do this efficiently, using the fewest lines of code, we can even put a loop inside a loop. Loops
inside other loops are known as nested loops.

• So that we can change the value of the y coordinate, make a new variable, named yindex.
• D ‘ ’ L
• ‘ ’ ‘ ’ ,
• ‘ ’ ‘ ’ ‘ ’
• Change the value of the y coordinates in the plot and unplot blocks to this same variable.

05.Iteration Page 88
let index = 0
let yindex = 0
basic.forever(() => {
for (let yindex = 0; yindex <= 4; yindex++) {
for (let xindex = 0; xindex <= 4; xindex++) {
led.plot(xindex, yindex)
basic.pause(100)
led.unplot(xindex, yindex)
basic.pause(100)
}
}
})

There! With only a half dozen or so lines of code, we have made our light travel through all the
coordinates on the micro:bit screen.

► Check: Make sure the students can read this code.

Here is what is happening to the values of the x & y coordinates as the program steps through
each line and loop inside the forever block:

1. In the outer of the two for loops, the value of the y-coordinate is set to 0.
2. The nested inner loop then sets the value of the x-coordinate to zero.
3. The corresponding led (x:0, y:0) is plotted and then unplotted.
4. Then the value of the x-coordinate is increased by 1 and step #3 runs again with the
coordinates now (x:1, y:0).
5. Then the value of the x-coordinate is increased by 1 again and step #3 runs again with the
coordinates now (x:2, y:0).
6. The inner loop keeps running like this until it has completed its loop with the value of the x
coordinate now 4.
7. With the inner loop complete, the program now runs the second iteration of the outer
loop, increasing the value of the y-coordinate by 1, then back to the inner loop which runs
4 more times stepping through values for x from 0 through 4.

Have the students use the Slo-Mo mode to watch the program step through the loops.

• By the end of the program run, how many times has the inner loop executed? 25
• Other than knowing that there are 25 LEDs and each is lit up once, how can you figure this
out? The outer loop loops 5 times altogether, once for every value of the y coordinate from 0
through 4. Each time the outer loop runs, the inner loop runs 5 times, once for every value of
the x coordinate from 0 through 4. 5 runs of the outer loop x 5 runs of the inner loop = 25
times the inner loop executes.

Mods
• If there is time, let the students experiment with changing the parameters to see how
these changes affect their program.
• What happens if you switch the positions of the nested loops, so the outer loop loops
through the xindex values and the inner loop loops through the yindex values?
• W ‘ ’ ‘ ’ ?

05.Iteration Page 89
‘While’ block: Micro:bit Alarm!
The while block is useful when you want your program to loop until a certain event happens or a
different condition is met.

For example, maybe you want an alarm to sound if someone shakes your micro:bit!
In order to turn the alarm off, you press the button A. Until you press the button, the alarm
should continue to sound!

Y ' ' ‘ ’

input.onGesture(Gesture.Shake, () => {
while (!(input.buttonIsPressed(Button.A))) {
for (let i = 0; i < 2; i++) {
music.playTone(262, music.beat(BeatFraction.Half))
music.playTone(523, music.beat(BeatFraction.Half))
}
}
})

Alarm

05.Iteration Page 90
• Can you read what this code does?
• Can you write out pseudocode that describes what this code does?

Example Pseudocode:
When someone shakes the microbit, while button A is not pressed, play the two tone alarm twice.
Keep playing the alarm tones until the user presses the A button.

To use sound with your micro:bit, you will need to connect it to some speakers or headphones.
See how to do this here: https://pxt.microbit.org/projects/hack-your-headphones

05.Iteration Page 91
Project: Get Loopy!

There are many different ways to use the three types of loop blocks.

Recall the different common repetitive actions you thought of back at the beginning of this
lesson.
• How will you use loops to create something useful, entertaining, or interesting?
• What might you make?

Here are some suggestions:


• Create an animated gif (looping image that changes) and add music that matches.
• Create animation that repeats for one of the melodies included in Make Code (like Happy
Birthday).
• Create different animations that run when different buttons are pressed.
• Create an alarm that includes sound and images. What will set the alarm off? What will
make the alarm stop sounding?
• Use servo motors to create a creature that dances and changes its expression while a song
plays.

Example

Hat Man Project

Hat Man Videos


micro:bit Hat Man

05.Iteration Page 92
micro:bit Hat Man - inside

This project uses the micro:bit light sensor to display a happy face when it is sunny, and a
frowning face when it is dark. The micro:bit is connected to a servo mounted on the inside of
the container, and the smile and frown are attached to plastic coffee stirrers with tape and hot
glue.

Reflection
Have students write a reflection of about 150–300 words, addressing the following points:
• Explain how you decided on your particular "loopy" idea. What brainstorming ideas did
you come up with?
• What type of loop did you use? For, While, or Repeat
• What was something that was surprising to you about the process of creating this
program?
• Describe a difficult point in the process of designing this program, and explain how you
resolved it.
• What feedback did your beta testers give you? How did that help you improve your loop
demo?

Assessment
05.Iteration Page 93
Assessment

4 3 2 1
Loops At least 3 different At least 2 loops are At least 1 loop is No variables are
loops are implemented in a implemented in a implemented.
implemented in a meaningful way meaningful way
meaningful way
Variables All variable names The majority of A minority of None of the
(parameters) are unique and variable names are variable names are variable names
clearly describe unique and clearly unique and clearly clearly describe
what information describe what describe what what information
values the variables information values information values values the
hold. the variables hold. the variables hold. variables hold.
Sound, Uses sound, Uses a only two of Uses a only one of None of the
display, and display, and the required the required required
motion motion in a way element in a way element in a way elements are
that is integral to that is integral to that is integral to used.
the program the program the program
Micro:bit Micro:bit Micro:bit program Micro:bit program Micro:bit
program program: lacks 1 of the lacks 2 of the program lacks 3
• Uses loops in a required elements required elements or more of the
way that is required
integral to the elements
program
• Compiles and
runs as intended
• Meaningful
comments in
code
Collaboration Reflection piece Reflection piece Reflection piece Reflection piece
reflection includes: lacks 1 of the lacks 2 of the lacks 3 of the
• Brainstorming required elements. required elements. required
ideas elements.
• Construction
• Programming
• Beta testing

05.Iteration Page 94
Standards

CSTA K-12 Computer Science Standards

• CL.L2-05 Implement problem solutions using a programming language, including: looping


behavior, conditional statements, logic, expressions, variables, and functions.

• CL.L3A-03 Explain how sequence, selection, iteration, and recursion are building blocks of
algorithms.

05.Iteration Page 95
Introduction

In this unit, we will be reviewing the concepts we covered in the previous weeks, and providing
“ - ”
We will also introduce a framework for keeping students accountable to the work they are doing
individually and in groups, and providing a rubric for assessment of the development process, as
well as the finished product.

It is important to allow students to practice accounting for the work they are doing on a short
“ - ” ,
weeks, it will be easier for you to keep track of what everybody is doing.

It also reinforces the important idea that how you solve problems is at least as important to
learning as whether you solved them at all (or even got the right answer). Programming is a
process of patient problem-solving, and finding ways to value, acknowledge, and reward the
problem-solving process is an important part of assessment.

06.Mini-Project Page 96
Review

Take this time to review the concepts we have covered so far.

Making
The micro:bit is very effective at bringing real things to life. It can be supported in a cardboard holder, attached to a
wand, or even sewn into fabric. The design thinking process is a helpful way to gather more information about the
person who will be using whatever you are designing.

Processing and Algorithms


The code you write for the micro:bit processes data from its inputs, and outputs it in some way. An algorithm is a series
of specific instructions, or steps, that solve a problem or accomplish a task.

Variables
Variables store information so that it can be accessed or referenced later. Some variables hold information that
changes, and some hold information that stays constant. It is important to name your variables with something that
explains what type of information it holds. Using variables in your code allows you to create algorithms that use
mathematical operations to perform the same calculations every time, even when the values of your variables are
different.

Conditionals
Conditional statements tell the computer when to do something. They are used to create branches, or decision points,
where a program can choose one path or the other based on the values of certain variables, or based on data from the

order for the enclosed statements to run.

Iteration and Looping


Portions of your code can be made to run over and over by using a Repeat or a For block loop. This allows you to
iterate over several different variables, or items in a group, and do something to each of them. You can also combine a
conditional statement and a loop by using a While block, which will repeat until a certain condition becomes true.

06.Mini-Project Page 97
Project: Mini-Project

This project takes approximately a week to complete. Most of that time is spent working on the project in a
makerspace or art classroom.

The mini-project is an opportunity for students to design a project that serves a purpose by solving a problem or
filling a need. It is also an opportunity to do two things:
• Show what you know
• Learn something new

Ideally, there should be a maker component to this project. This is a real world component that works with the code
on the micro:bit to do something unique.

Students are asked to each propose an original independent project. Students are allowed to work on the same idea,
but they cannot turn in the same code. They can, and should work collaboratively, solving the same kinds of
problems together, but the projects they turn in should be unique and original.

Showcasing Student Work


Students will be showing their work regularly to each other in informal ways. Think about also organizing a day or an
evening when parents, administrators, or others from the community are invited to come and view the students'
projects.

We find that a "science fair" type of setup works well here, with students stationed at their own tables, showing off
and demonstrating their project. An event like this works well for these reasons:
• A real world audience for the work students have done can be very motivating
• It is a chance for people who are not familiar with the micro:bit to appreciate the finished product
• It provides good feedback to students about how someone interacts with their product
• It is a chance to have real conversations with the people behind the product, rather than just viewing the
product on display by itself
• Finally, and most importantly, it is a chance to bring the community together to celebrate the great work all of
your students have done!

Assignment
• Create an original project using the micro:bit.
• Incorporate a physical component to the project.
• Demonstrate the use of one of the following concepts:
○ Input / Processing / Output
○ Variables
○ Simple Circuits
○ Iteration/Loops
○ Conditional Statements

Project Ideas
• “N I ”F
• Make a Moving Monster
• Make a musical instrument
• Fishing Game
• Make an Air Guitar (uses while loop to do tempo and pitch)
• Screensaver
• Screensaver that uses other inputs to draw
Interactive book

06.Mini-Project Page 98
• Interactive book
• Binary Clock or some other way to represent numbers visually

View projects at the following sites for inspiration:


• http://make.techwillsaveus.com/bbc-microbit
• http://microbit.org/ideas/
• https://twitter.com/MicroMonstersUK
• https://pxt.microbit.org/projects

Examples

Toss the Ball


This is a skill game in which an aluminum foil ball is thrown into a plastic cup. Copper tape lining the sides and
bottom of the cup completes the circuit when the ball touches it.

micro:bit Bullseye Project

06.Mini-Project Page 99
This is a skill game in which tennis balls are thrown underhand at one of the three rings, which are lined with
aluminum foil so they complete a circuit underneath when the ball makes contact with the ring.

micro:bit Storybook

This is a prototype of a storybook that could use the micro:bit to display animations for part of the story. Copper
tape is used on the underside of the paper flaps to make contact between the GND pin and each of the other pins in
sequence.

Work Logs
Because students are working on the projects in class, and much of the benefit comes from working together to solve
problems, they should account for the work they are doing by writing a work log.

, , I ’
more than thirty seconds or so to write up a work log. Students should do one for every class. A shared Microsoft
OneNote notebook is a great way to keep a work log that students can update regularly. Alternately, you might use a
collaborative shared document, or your classroom management system, or even e-mail.

Sample Work Log


April 11
20 min. Created code that reacts when pins P0 and P1 are pressed.
10 min. Talked with Mr. Kiang about how to attach wires so they won’t fall off
20 min. Put target back together with pins
10 min. Helped Cody with attaching his scoreboard

06.Mini-Project Page 100


10 min. Helped Cody with attaching his scoreboard

Reflection
At the end of the week, students should compose a final reflection that summarizes the process of their learning over
the course of the week. They should go back through their work logs and talk about the following:

• Talk about one challenge you faced in creating this project, either a challenge in coding or in making the
artifact. How did you overcome this challenge?
• What did you demonstrate that you already knew?
• What was the new thing you learned in order to make this? How did you learn about it?
• Who in the class provided help to you along the way? How?
• Describe one specific thing you are proud of in this project.
• What would you do differently next time?
• If you had another week to work on this project, what might you add or improve?

Sample Reflection (excerpt)


“I spent this week finishing up little details with my program, making it work better and more user friendly. The
part that surprised me the most was the little things that kept popping into my head, little suggestions that could
potentially be good to add, but might not be necessary or even useful. At the beginning of the assignment, I just
added them as quickly as I thought of them, but as the project neared the midpoint and conclusion, I find myself
considering if I actually need them (as previous additions have been since quickly deleted). Another thing that I find
interesting about this is that it is a rather specialized project. Not many people would use it except for me.
However, this is supposed to be easily used by other people, so I have to take them into consideration as I design
the project. I also realized that I had, at some point, broken part of my code without realizing it, so I now have to
fix part of it. The reason that it is a problem is because I added a lot of code at once without deleting it, which is
unfortunate. Next time I will add small amounts of code and test it first.”

Assessment

4 3 2 1
Code - Code very effectively Code only partially Code only partially Code does not
Show what you demonstrates the use of previous demonstrates demonstrates demonstrate
know concept(s). Variable names are previous concepts, previous concepts, previous concepts,
unique and clearly describe what and/or is not and/or is not is not efficient,
information values the variables efficient. efficient, variable variable names not
hold. Code is highly efficient. names not clear. clear.
Code - Code very effectively Code only Code only Code does not
Show something demonstrates the use of new minimally minimally demonstrate new
new concept(s). Variable names are demonstrates new demonstrates new concepts, is not
unique and clearly describe what concepts, and/or is concepts, and/or is efficient, variable
information values the variables not efficient. not efficient, names not clear.
hold. Code is highly efficient. variable names not
clear.
Maker Tangible component is tightly Tangible Tangible No tangible
component integrated with the micro:bit and component is component does component
each relies heavily on the other to somewhat not add to the
make the project complete. integrated with the functionality of the
micro:bit but is not program.
essential.
Work Logs All work logs submitted on time, One late or missing Two late or missing More than two late
and accurate work log and/or work logs and/or or missing work

06.Mini-Project Page 101


and accurate work log and/or work logs and/or or missing work
work logs not work logs not logs and/or not
accurate nor accurate nor accurate nor
sufficiently sufficiently detailed. sufficiently detailed.
detailed.
Reflection Reflection piece describes: Reflection piece Reflection piece Reflection piece
• Development Process lacks 1 of the lacks 2 of the lacks 3 of the
• Something new required elements. required elements. required elements.
• Something proud of
• Future mods

06.Mini-Project Page 102


Activity: Collaboratively Independent

Teachers want their students to collaborate on projects but they also want to be able to hold them accountable
for getting their work done. Many teachers struggle with assessing exactly how much each individual contributed
, “ ”

The Mini-Project (and the Final Project) are not group projects. Students are asked to propose their own
independent project and are expected to get it done. But they are not on their own in this process! We build in
frequent opportunities for students to collaborate and share the collective knowledge of the class as they go. We
“ ”

Here is how we structure our classes:

Beginning of class
For groups of 15 or so, have students each briefly (no more than 30 seconds or so) report on their progress in
front of the group:
• One-line description of project
• Their progress so far
• Something they are going to work on figuring out today

It is important that everyone else is listening to each project and volunteering their help or solutions if they are
figuring out the same thing or if they have solved that problem in a previous class.
Example:
I’m working on a pinball machine. So far I have done the board and the ramp. Today I am going to be working
on wiring the bumpers so that when the ball hits the bumper, the micro:bit detects it and displays the score.

Sample response from a classmate:


Yesterday I wired up my targets so that when you throw a ball it keeps score. I can show you how I did it.

Ideally students who are working on projects should be aware of what other students are working on and what
they are figuring out. It creates more opportunities for collaboration in the classroom and can encourage
students to seek help from each other rather than all waiting in line to talk to you.

I’ ’ F
15 or 20 students, you may want to split them into two or three larger groups and have them report out to each
other.

During Class

06.Mini-Project Page 103


During Class
This is a time to circulate and check in with students individually, starting with those students who seem to still be
stuck from last time. For the most part, students should be working on their projects in small groups, helping
each other wherever and whenever possible.

End of Class
, “ -in- ” G
students together and have them move from table to table while each student presents one thing that he or she
figured out during the class. This is really an informal presentation, and it is understood that it is not finished at
; “ ”B ,
one throughout the classroom, almost like physicians making rounds in a hospital. This is an important way to
, “ - ” q

Work-in-progress reports should be short, no more than twenty or thirty seconds. If you have a large class, you
might divide the class into several large groups and have them present to each other.

06.Mini-Project Page 104


Standards

CSTA K-12 Computer Science Standards

• CL.L2-03 Collaborate with peers, experts, and others using collaborative practices such as
pair programming, working in project teams, and participating in group active learning
activities.

• CL.L2-04 Exhibit dispositions necessary for collaboration: providing useful feedback,


integrating feedback, understanding and accepting multiple perspectives, socialization.

• CL.L2-05 Implement problem solutions using a programming language, including: looping


behavior, conditional statements, logic, expressions, variables, and functions.

06.Mini-Project Page 105

You might also like