LEARN.PARALLAX.COM
Published on LEARN.PARALLAX.COM (https://learn.parallax.com)
Home > Making micro:bit programs

Making micro:bit programs

What it’s about

The micro:bit module will be in the driver’s seat of your cyber:bot robot, and it also has many features of its own. In this tutorial, you will learn how to make programs, called “projects,” to use the micro:bit module’s pushbuttons and LED display. Along the way, you will learn some basics of Makecode programming to remember and use values, do math, make decisions, and repeat actions.

Before you start

You will need:

  • a micro:bit module
  • a USB A to microB cable
  • to complete the Get Started with micro:bit and MakeCode tutorial with your Windows, Mac, or Chromebook computer

After you finish

Once you have completed these activities, you will be ready to expand the capabilities of your micro:bit.

LED Matrix

The micro:bit module has a 5×5 matrix, or grid, of LEDs on the front of it. An LED, or Light Emitting Diode, is an electrical component that allows electricity to flow through it in only one direction.

When an LED is hooked up in the proper direction and electricity is applied, the LED lights up. The 25 LEDs on the face of the micro:bit module are already connected so we do not need to worry about their connected direction, however, additional LEDs can be connected to the cyber:bot using the breadboard.

Collectively these 25 LEDs form the display of the micro:bit module. The micro:bit module can be programmed so that the LEDs can show images, scroll text across the screen, or be individually illuminated to a variety of brightness levels.

Each LED row (x-axis) and column (y-axis) is numbered 0 through 4, so each LED can be identified individually. But first, we will try convenient, ready-made instructions for displaying scrolling text and predefined images. 

Using the micro:bit module Reference

The three pages that follow this one will cover what you need to know to work through the cyber:bot tutorials. However, it is by no means entirely comprehensive.

Scrolling Text

Scrolling text across the display is a very useful way to get information from your micro:bit program. When you have your micro:bit on your cyber:bot robot, this is a good way to display values from the robot’s sensors.

To scroll text across the display, use the aptly named display.scroll method. The text you want to display goes inside quotation marks ” “, and that goes inside the method’s parentheses ( ).

Example project: hello

  • Connect your micro:bit module to your computer with its USB cable.
  • In a browser, go to makecode.microbit.org to open the micro:bit Makecode Editor.
  • Enter and name the hello project.
    (See Save & Edit Projects.) 
  • Click Send to micro:bit.
    (See Flash Projects with MakeCode Editor.)

You should see the word Hello scroll across the display one character at a time.

  • Did you miss it? Press the reset button on the underside of the micro:bit module to see the Hello message repeat.

How the Hello Project Works

The only used block makes the text appear on the display. The “Hello” text in quotation marks is a parameter of the show string method, and so goes inside its parentheses.

Your Turn: Your Name

  • Make a project to scroll your first name across the display.
  • Modify your project to scroll your first name across the display wait 5 seconds, then scroll your last name across the display.

Premade Images

Sometimes you might want the micro:bit module to simply show an image instead of scrolling text. We can do this with the show icon block, using premade images from the Image object. For example: show icon (DUCK).

Example project: Image

  • Enter, name, and flash the image project to your micro:bit.

You should see a duck appear on your micro:bit module’s LED matrix, like the picture shown above.

  • Replace DUCK with a different premade image from the lists below, and re-flash your program. 
  • Try some more. There are many to choose from!

Try This: Image Sequence

You have displayed a single image with a single block of code. To display a series of images, place the pause block between them. The pause block pauses the micro:bit module for a specified number of milliseconds, giving you time to see the image on the display. For example:

…will show an image of a heart for half a second (500 milliseconds), then show an image of a small heart for another half a second. Try it!

Example project: images

  • Enter, name, and flash the images project to your micro:bit.

Your Turn – Heartbeat

In the project images, the heart looks as if it beats once.

  • Can you modify your project to make the heart to beat 5 times?
  • After you get the heart to beat 5 times, make the heart beat faster.
  • Can you make the heart beat slower?

Custom Images

There are two ways you can create custom images from individual pixels on the micro:bit module’s display, the first by using the plot block in the more section of the Led category, or the second by using the show led in the basic category. 

The plot method has three parameters: x, y, and brightness:

The arguments for x and y indicate the pixel’s position in the micro:bit module display’s coordinate plane. The brightness argument controls the brightness (0-255) of the pixel.

Example project: two_pixels

To see how this works, try the following program which lights up two LEDs.

  • Enter, name, and flash the project two_pixels to your micro:bit.

How the two_pixels project works

The first block plot x (0) y (0) brightness (255) lights up the pixel is located at (0,0) which is the top left of the display. It is set to the maximum brightness of 255.

The second blockplot x (1) y (3) brightness (127) lights up the pixel located at (1,3), which is in the second column from the left and down 4 rows. The brightness is only 127, so it is significantly dimmer than the first pixel.

Example project: medium_box

There’s a much easier way of setting the LEDs when you don’t care about the brightness of them. Using the following project, see how a medium-sized box can be made by lighting up 8 pixels in the middle of the micro:bit module’s display.

  • Enter, name, and flash the project medium_box to your micro:bit

  • It’s as easy as just clicking which squares you want to turn on.

Your Turn

  •  Try doing the same thing only using the plot command.
  • Try creating a large box that uses all of the pixels on the outside edge of the display.
  • Try making a program for a custom image of your own creation.

Remember and Use Values

Variables

Variables are names you can create for storing, retrieving, and using values in the microbit module’s memory. Here are three example variable declarations from the next program:

A variable can hold different kinds of values, such as integers (whole numbers), decimal numbers, and characters. Each of these kinds of values uses a different data type.

The declaration a = 42 creates a variable named a. The value 42 is an integer, so Makecode automatically assigns the int data type to the a variable, and gives a an initial value of 42.

Next, c = “m” declares a variable named c and initializes it to the value “m.” Since “m” is a character, Makecode assigns c the data type str for storing strings or text. 

Then, d = 42.06 declares a variable named d. The value 42.06 is a decimal number, so Makecode assigns d the data type float, which can hold floating-point decimal values.

Example project: variables

Now that you know how code can store values to memory, how can it retrieve and use them? One way is to simply pass each variable to a method’s parameter. 

Here is an example, where show string uses the display to scroll the value of the variable inside the parentheses.

  • Enter, name, and flash the project variables to your micro:bit.

The display will scroll the number 42, then it will scroll the letter m (shown below), and then it will scroll the number 42.06.

Solve Math Problems

Arithmetic operators are useful for doing calculations in your program. In this activity, we’ll focus on the basics:

  • addition (+)
  • subtraction (–)
  • multiplication (*)
  • division (/)
  • modulus (%, the remainder of a division calculation)

Example project: simple_math

The example project simple_math uses the addition operator (+) to add the variables a and b together. The assignment operator (set c to) is used to store the result in the variable c. It also displays the result on the micro:bit.

  • Enter, name, and flash the project simple_math to your micro:bit, then watch the display.

Your Turn – Experiment with Other Arithmetic Operators

You still have –, *, / and % to try out!

  • In the project simple_math replace the addition (+) operator with the subtraction (–) operator. Be sure to replace both instances of + in the program.
  • Re-flash the program to the micro:bit.
  • Verify the result on the display.
  • Repeat for the multiplication (*), division (/), and remainder of (%) operators.

Make Decisions

Your cyber:bot will need to make a lot of navigation decisions based on sensor inputs. Computer programs tend to make decisions by testing whether or not a condition is true, and if it is true do one thing, else, do another.

For making these kinds of decisions, comparison operators come in handy.

  • compare-equals (==)
  • greater than (>)
  • less than (<)
  • greater than or equal to (>=)
  • less than or equal to (<=)

Simple Decisions

The project simple_decision demonstrates single-operation decision-making. It compares the value of a to b, and sends a message to tell you whether or not a is greater than b, with an if…else block. 

If the condition (a > b) is True, it executes the if block’s code block: show string (“a is greater than b”). If it so happens that a is not greater than b, it executes the else code block instead: show string (“a is not greater than b”).

Example project: simple_decision

  • Enter and name the project simple_decision into the code editor exactly as shown.
  • Flash the project to the micro:bit.
  • Look at the display to make sure you got the right message.
  • Try swapping the assigned values for a and b.
  • Re-flash the program and verify that it is displaying the other message.

Make sure you have the proper messages within the proper if…else container as shown above.

Try This – Only if

Maybe you only need a message when a is greater than b. If that’s the case, you could cut out the else block and its code. So, all your code would need is the one if block, like this:

  • Modify and re-flash your code as shown above.

Your Turn

  • Make a project using the compare-equals operator (=) that displays a message only when a is equal to b.

More Decisions

Maybe your program needs to monitor for three conditions: greater than, less than, or equal. For this, you could use an if…else if…else block. 

Example project: more_decisions

  • Enter, name, and flash the project more_decisions to your micro:bit.

You can chain more else if blocks after if. The example above only uses one else if but you could use more. Each condition is tested in order, and after the first true condition is found, its code block is executed and the rest of the block gets left behind. 

Your Turn

  • Make a project that uses two or more else if blocks that are true, with code blocks that display messages.
  • Flash the project to prove that only the first true else if condition’s message gets displayed.

Boolean Operators

Sometimes, you need to test whether two or more conditions are true at the same time. A program can handle multiple conditions with the boolean operators, such as and and or. For example, this block’s code will execute only if a is greater than 50 AND b is less than 50:

Another example: this one prints the warning message if a is greater than 100 OR b is less than zero.

Your Turn

  • Try the above blocks in a project.

Count and Repeat

Many robotic tasks involve repeating an action over and over again. Next, we’ll look at two options for repeating code: the for loop and the while loop. The for loop is commonly used for repeating a block of code a certain number of times. The while loop is used to keep repeating a block of code as long as a condition is true.

A for Loop is for Counting

A for loop is typically used to make the blocks in a code block repeat a certain number of times. For example, your cyber:bot may use five different values to make a sensor detect distance, so it needs to repeat a certain code block five times. For this task, we use a for loop. Here is an example that uses a for loop to count from 1 to 10 and display the values.

Example project: count_to_ten

  • Enter, name, and flash the project count_to_ten to your micro:bit.
  • Make sure the cyberbot Extension is included in your new project.
    (See Add modules to your micro:bit).

How the For Loop Works

The figure below shows the for loop from the last example project count_to_ten. It labels the elements needed to control how the for loop counts.

Variable: You must have a variable that the code will change while it is executing the for loop. You do not need to declare the variable before this. It is best to name the variable after its purpose. In this example, the variable was a counter, thus it is named counter. It is very common to use the word index or the letter i as the variable in for loops.

The range block: The range(start, end, step) block is often used with for loops. The start argument sets the initial value of the previously declared variable. The stop argument sets the value the for loop will stop at. The step argument determines how much to increment the variable by for each iteration.

The first time through the loop, the value of counter is set to 1. So, show number (counter) displays the value 1. The next time through the loop, Makecode increments the value counter by 1. After the display is finished scrolling, the for block checks to make sure the condition counter ≤ 10 is still true. Since counter now stores 2, it is true since 2 is less than 10, so it allows the code block to repeat again. This keeps repeating, but when counter gets to 11, it does not execute the code block because it’s not true according to the counter ≤ 10 condition.

Try this: Adjust Initialization and the Range Block

As mentioned earlier, the range(start, stop, step) block defaults to incrementing the variable by 1 each time through the for loop. You can adjust the step argument so that the for loop is incremented by 2, 5, 1000, -1, or any other integer. Do note that if your step is a negative value, you will need the start value to be larger than the stop value.

  • Rename your project as count_higher_in_steps.
  • Replace the for block in the project with this:

  • Flash the modified project to the micro:bit and watch the output on the display.

A Loop that Repeats while a Condition is True

In later chapters, you’ll use a while loop to keep repeating things while a sensor returns a certain value. Let’s try counting to ten with a while loop:

  • Enter, name, and flash count_to_ten_again to your micro:bit.

Assignment Operators

While loops often make use of certain assignment operators. Such operators take the value on the right-hand side, perform an operation, and assign the result to the value on the left-hand side. Every time you declare a variable, the equal sign (=) is functioning as an assignment operator. But there are more, less-familiar assignment operators.

For example, the change block adds the value on the right-hand side of it to the variable. You can also subtract from it by simply using a negative value in the change block.

Want to condense your code a little? You can use the change block to increase the value of counter inside without having to type counter twice.

Using the True Constant

We could also make the loop repeat forever by using the word True instead of the condition counter < 10.

So why does this work? A while loop keeps repeating as long as the condition that follows the word while is true. The word True is a pre-defined constant, so while True is always true, and will keep the while loop looping. Can you guess what while False would do?

Your Turn

Try these different while loops in the project count_to_ten_again. What happens?

  • Try while True
  • Try while False

Pushbuttons

The micro:bit module has two pushbuttons labeled A and B, to the left and right side of the LED display. This kind of button is sometimes called a tactile switch, or tact switch for short. The micro:bit module can be programmed to respond to these buttons being pressed. In your projects, each button already exists as an object, and they can be referred to as button_a and button_b.

For example, if you want something to turn on only when button A is being pressed, you can use button A is pressed. The same can be done for button B or both A and B.

Example: is_pressed

You can make a block for each button to tell if it is pressed. The button A is pressed method will return either True or False depending on whether or not button A is currently pressed. These methods often work well with conditionals. For example, the following program displays a check mark if button A is pressed. Otherwise, it will display an X. 

  • Enter, name, and flash the project is_pressed to your micro:bit.
  • Press button A to see the display change.

Try This

  • Use the display to show the letter A when the A button is pressed.
  • Use the display to show the letter B when the B button is pressed.

Example project: on_pressed

Another commonly used method of the buttons is to run a set of blocks as soon as the button is pressed. This is what we call an interrupt because it interrupts the program to run its own blocks.

For example, the project on_pressed will display a scrolling hello when button A is pressed. If nothing is pressed, then nothing will be shown.

  • Enter, name, and flash the project on_pressed to your micro:bit.

Your Turn

  • Make a project to show a custom image for 10 seconds if button A was pressed and then disappears after.
  • Make a project to show a flash B 10 times when button B is pressed instead of button A.

Making Functions

In some of the earlier examples, your projects used a function named pause. This function made the micro:bit wait for a certain amount of time before allowing it to execute the next block in your project. 

A function is a block of code that your project can call to make it do a certain job. In the case of pause, the block of code is tucked away with other functions in the microbit. When your project starts, it gets access to pause and several other functions through the categories. 

Functions aren’t only found in places like the categories. You can also make your own functions and call them, all from within the same project. This is especially useful when you have a group of blocks that gets used in several different places in your program. After putting that group of blocks into a function and giving it a name, it just takes one block to call the function at any point. 

Imagine you have ten blocks that need to be executed at four different locations in your project. With a function, you can reduce the extra code from forty blocks to fifteen. That’s ten blocks of code, one block to define the function’s name, and then single-block function calls from the four locations. 

Since functions are such an important tool for keeping your program small and organized, this activity will guide you through adding functions to your Makecode projects and calling them.

Define a Function

The following project defines one function. The smile function simply displays a smile on the microbit’s display. It doesn’t take any inputs nor does it return anything.

Function definition: smile

  • Examine the smile function definition project below.

To make a function all you need to do is go to the functions category in the advanced section, then press make a function. After that, you can type in the desired name and choose the variable types that you want, you’re also able to name the variables that are used. If you add a return to the function a new type of call block becomes available that you can use to save the returned value in a variable.

  • Enter, name, and flash the smile function definition project above to the micro:bit module.

The project doesn’t do anything! We defined a function but we didn’t call upon it.

  • Add a call to the function in the smile project, and re-flash.

Example project: emote

The project smile didn’t have a very complex function. Let’s see what else we can do with functions! For example, we can nest if…else… blocks inside functions.

  • Enter, name, and flash the project emote to your micro:bit.

In the emote project, our function now has an input. That input is either the word “happy” or the word “sad”. When the function is called, it will use the nested if..else if..else block to determine if the feeling is happy, sad, or not understandable!

  • Replace the word “happy” with “sad” and re-flash the project onto the microbit. What do you expect to see on the display?

Example project: adding

While the function in the emote project has an input, or parameter, that we can pass through it, it still doesn’t have anything it returns. The functions in the project adding both have parameters and return values.

  • Enter, name, and flash the project adding to your micro:bit.

Notice how the add_one function takes one input. It then takes the input and adds one to it. It then returns the new result of that addition.

The addTogether function takes two inputs. It then adds those two inputs together and assigns the result to a new variable called result. It then returns that result.

Since neither of these functions cause the value to display, we can instead call them inside of the display’s show string method. This means we can pass functions through methods!

Global vs Local Variables

Local Variables

So far, we’ve declared variables inside a function block—the indented portion of code that follows declaration of a function—which means they are local variables. Only the function declaring a local variable can see or modify it. Also, a local variable only exists while the function that declares it is using it. After that, it gets returned to unallocated memory so that another function (like loop) could use that memory for a different local variable.

Global Variables

If your program has to give more than one function access to a variable’s value, you can use global variables. To make a variable global, just declare it outside of any function. Then, all functions in the program will be able to modify or retrieve its value. 

Example project: store_retrieve_global

The next example project declares a global variable called k, assigns a value to it, and then uses its value from within a function. In contrast, the variable called value is a local variable and only exists within the add_k function. If you try to show sting (value), you will only get a 0.

  • Enter, name, and flash the project store_retrieve_global to your micro:bit.

Example: store_change_retrieve_global

If you want to permanently change the global variable from within the function, you must use the keyword global to call upon the global variable. In the project store_change_retrieve, k is created as a global variable with the value 5 assigned. Each time k is called upon in the function add_k it gets incremented by 1.

  • Enter, name, and flash the project store_change_retrieve_global to your micro:bit.

  • The display will first scroll 9, then 10. Do you understand why?

DISCUSSION FORUMS | PARALLAX INC. STORE

About | Terms of Use | Feedback: learn@parallax.com | Copyright©Parallax Inc. 2024


Source URL:https://learn.parallax.com/courses/making-microbit-programs_makecode/
Links