Coding Fundamentals

back to main

Sequencing

Simple: computers do things in order.
In your program, YOU decide the order!

ExampleUse Snail Mode for further clarity…
* Create your own animation!

Conditionals

When your program needs to make a choice, you use a conditional statement.  The most common structure is if – else if – else.

Example – Choose a button A or B
* Can you add a behavior for when both A & B are pressed together?

Loops

When your program needs to repeat a sequence, you use a loop: while and for loops are often used.

Example – Keep loopin’ while you hold a button
* Add your own Loopy behavior.

Example 2 – Stopwatch (from 0 to 9)
* Can you reverse it to be more like a timer?

Variables

Your program often needs to keep some state information.
How many items did the user add to their shopping cart?
What is the current game score?

You can create as many variables as you need to store useful information.

Example – Tally Counter
* Can you add a RESET button like this product below?

How about a minus AND a reset?

Note: We saw earlier that for loops include index variable to keep track of loop iterations.

micro:bit Inputs

Looking at the <input> tab you can see blocks that trigger on certain input events:

  • On button pressed
  • On shake

There are also blocks that help you read in:

  • time
  • acceleration in 3 dimensions
  • pitch or roll
  • compass heading or magnetic force
  • light
  • temperature

You can also attach various external sensors and other Integrated Circuits to the various I/O pins.

Example – Graphical Light Meter
* Can you make this meter more exact by using the Led -> Plot Bar Graph block?

Projects

  • Make a Timer:
    • Code one button to count up to the desired # of seconds
    • Code another button to start the timer and display the seconds as they count down to zero

  • Rock Paper Scissors Game:
    • Code the micro:bit to come up with a different random number between 1-3 every time you shake it.
    • Map each number to Rock, Paper or Scissors, and display the corresponding image (see Show Icon block, bottom row, to save time) on every shake
    • Bonus: you can keep score by pressing “A” when you win, “B” when the micro:bit wins.  After each game, press the correct button and display the current score.

  • Walkie Talkie – Use the “Radio” blocks to communicate between micro:bits:
    • Both sides need to have the same “Group” set in On Start block.
    • You can send strings or numbers
    • You can receive either strings, numbers, or name/value pairs, but no combination of those in one program
    • For instance – make pressing A send  number ‘1’, and  pressing “B” send number ‘2’
      If receiver gets ‘1’, show one image, when it gets ‘2’ show another.
      For instance, it could be used to send True/False data – show Tick and X.
    • You can make 1 micro:bit send to many.
    • You can also make a chain of communicating micro:bits.