If-Then-Else Statements

How to code if-then-else statements with Makecode for micro:bit

Description

This activity guides you through setting up an If-Then-Else statement in MakeCode. The code displays one of two icons depending on the value of a variable. The variable gets set to a value using a random number generator.

Programming Language

MakeCode Blocks

Difficulty Level

Beginner

Age Range

9 and up

Materials

Optional materials for this project are:

Programming the micro:bit

Develop the problem statement

The idea of this program is to demonstrate If-Then-Else statements. The problem I am addressing is how to set up something with a trigger that will allow a student to start the if-then loop a few times so both branches are selected.  Here is the problem statement I used:

When a trigger is initiated, set a variable to either 1 or 2. If the variable is 1, show a heart. If it is 2, show a stick figure. Clear the screen after each iteration to make it clear what the selection was.

Write the algorithm

The algorithm needs to get a little more specific about what is going to cause the alarm to sound and how long it sounds. Here is my version:

  • Check light level
  • if any light is present
    • play siren sound for 2 or 3 seconds
  • Repeat the above steps forever

Write the pseudocode

Here is the algorithm I wrote:

  • On button A pressed
    • Set random number to 1 or 2
    • If random number = 1
      • Show heart icon
      • pause for 500 milliseconds
    • Else
      • Show stick figure icon
      • pause for 500 milliseconds
    • End If
    • Clear screen
  • End on button A pressed

Write and test the code

Here is a link to the code I wrote:

If-Then-Else Example