Micro:bit Basics for Teachers Part 3: MicroPython

About: ElecFreaks is an open design house founded in March 2011. Our goal is to create rapid prototypes and give small-batch manufacture solution for makers and startups. With over 50% staff as engineers and expand...

Teachers: learn the basics for teaching your students to code with the micro:bit using MicroPython.

Step 1: Hardware Components

Step 2: Story

Step 3: Introduction

In part one of our micro:bit series, we learned about the hardware, and in part two, we learned how to code using Javascript blocks with the micro:bit.

Today, I will be covering the basics of coding with MicroPython. I will focus mainly on using the micro:bit’s LED display. I will start by walking through a simple code and how it works.

I’ll show you where to find common MicroPython commands used in coding and then we will walk step by step through writing the code to measure temperature with your micro:bit. There is so much more that you can do with the micro:bit than what we will cover in this video. At the end of this lesson I will include a list of resources including the reference guide to MicroPython, lesson plans, and written code for you to use in your classroom.

Step 4: Why Learn Python?

First of all, why learn Python?

As of 2018, Python is the fourth most popular coding language in the world. It’s commonly used by scientists, data scientists and web developers.

The code we’ll be using today is actually called MicroPython. It’s a version of Python designed specifically to run on microcontrollers. MicroPython is opensource, which means anyone can see all of the code, and anyone can edit it and submit their edit for review.

The Reference

Go to microbit.org, and click ‘let’s code.’ Scroll down to Python and open the code reference in another tab.

This reference has everything you need for coding with MicroPython. It's a good idea to keep it open when you are coding or helping your students to code in MicroPython.

The Editor

Unlike the Javascript editor, the Python editor doesn’t include blocks, although it may in the future.

The very first line of your code is “from microbit import *” The star symbol indicates the word “all”. So, by writing this command first, you are telling the MicroPython editor that you want to use (or import) all of the code needed for the micro:bit to work. The code needed to make the micro:bit work is called a library.

Step 5: Libraries

What is a library? A library is a larger collection of code that can be referenced by using a short command in the editor.

Take the command - display.scroll - as an example. The command display tells the micro:bit you want something to be displayed on the LED grid and .scroll tells your micro:bit to scroll the letters within the parentheses and quotations across the micro:bit LED grid.

Since micropython is opensource you can actually view all of micropython’s libraries here: https://github.com/bbcmicrobit/micropython

If we navigate to the library for display (https://github.com/bbcmicrobit/micropython/blob/master/source/microbit/microbitdisplay.cpp) you can see that there are 579 lines of code in this library. Thankfully, they have all been defined by a simple command, so you don’t have to write all 579 lines in your code. All you have to write is .scroll.

There are many different types of libraries that you can use and import. The micro:bit library MUST be included in your code in order to use the micro:bit with MicroPython. It includes code to let you control the temperature sensor, accelerometer, LED grid, pins and everything else on your micro:bit’s hardware.

Some special code isn’t included in the basic microbit library, so you’ll have to import it separately. For instance, say you wanted to generate a random number when you shake the micro:bit. You would need to type “import random” to import the random module, since the code you need to generate a random number is not included in the basic micro:bit library.

If you want to use music, you have to type “import music.”

If you’re getting creative and you want to add some extra neopixels to your project, you’ll have to “import neopixel.”

Unfortunately, the micro:bit currently doesn’t support the onboard bluetooth radio with Python. The Python code for BLE is a library as well, and it’s simply too many lines of code to fit on the micro:bit.

While True

You’ll see "while true" a lot when you’re coding in MicroPython. “While true” basically means that while some condition is true, keep looping over some code.

It might be a bit confusing at first. What, exactly, is true? Most values in Python are true.

Since “While True” doesn’t define what condition needs to be true for it to continue looping, it will keep looping forever unless you type ‘break.’ Since it loops forever, it is used similarly to the ‘forever’ event handler in the blocks.

Step 6: Hello World

Let’s walk through what the code within the While loop does. We already talked about the display.scroll command. This command will scroll whatever is written in the parentheses across the LED display.

Since the 70s, it’s been tradition for your first program to say ‘Hello world.’

Images

Our second command - display.show will show whatever is in the parentheses on the LED display. In this case it will show an image of a heart.

There are a lot of built in images that you can use with the image command. The list of images can be found in the micro:bit reference under “images”. You can also create your own images which we will talk about a bit later.

Sleep

The last part of this code is sleep(2000). Sleep is the command for “pause” or “wait”. This command tells the micro:bit to stop the display and wait the amount of time in the parentheses. When you are coding with your micro:bit the default time length is in milliseconds. So in this case, the display will stop and wait 2000 milliseconds which is the equivalent of 2 seconds, before repeating the sequence.

Download and Run your Code

Now that you know what this code does, run it!

Press download to download your code as a hex file. Make sure your micro:bit is plugged in. Drag and drop it to upload it to your micro:bit and see what it does!

The micro:bit says “Hello world”, then shows a heart. Then it waits two seconds, then it starts over again.

Building the Temperature Sensor

Go ahead and delete your code. Just like we did in the last lesson in Javascript, we’re going to build a temperature alert that alerts you if the temperature gets too hot or too cold.

Before we start writing our code we need to think about how we want our thermometer to work. We want our thermometer to show us if the temperature is too hot or too cold. There are a few ways to do this, either by playing a noise, showing a display, or both.

For this demonstration we are going to have the thermometer scroll the temperature and then show a display to indicate if the temperature is within the desired range or not. Our desired temperature is 28 degrees Celsius. If the temperature is higher than 28 degrees Celsius we will have the LED display show an angry face. Or else If it is less than 28 degrees we will have the LED display show a snowflake. If the temperature is exactly 28 degrees then that means it is in the desired range and we will have the micro:bit display a happy face.

Snippets

We’re going to make a forever loop using while true. Type ‘wh’ and hit the TAB key. Replace ‘condition’ with True.

Snippets are a cool way to avoid typing. You can access snippets from the "Snippets" button, but it's a lot quicker and easier to learn the triggers for the different fragments of code.

Step 7: Get the Temperature

While our loop is running, let’s get the temperature. I’ll search the reference to see how to do that.

In the reference, I find the method microbit.temperature() I can actually just type temperature() since I’ve already imported the micro:bit library. I’ll save the temperature to a variable called “temp.”
temp = temperature() 

A variable is used to label and store information in your program. By creating a variable called “temp” we can store the temperature that is detected by the micro:bit. Then whenever you want the micro:bit to use the stored value, in this case the temperature, all you have to do is write the word temp in your code.

Now, let’s show the temperature.
Display.scroll(temp) 
Add a brief sleep, 500 milliseconds, so that our micro:bit gets a break.
sleep(500) 

Saving

Save your code. Unlike the Javascript editor, pressing save won’t save your code in the browser. Instead it will download your code as a Python file on your computer.

Download and run the temperature code that you just wrote.

Debugging

Uh oh, looks like we have an error. The error is a type error. Although this code should work (since it’s included in the reference samples) it doesn’t for some reason.

So what is a type error? Data types are a bit out of the scope of this tutorial, but I’d recommend reading more about them in the tutorial here. Because we want our micro:bit to display a number rather than letters, we’ll have to change our temperature value to be a string. To do that, we simply write “str” in front of (temp) like this:
display.scroll(str(temp))

Now when we upload the code, we can see that the code is working.

Errors

MicroPython is kind of picky about how the code is written. If your micro:bit displays a NameError you may have typed something incorrectly like accidentally including a capital letter that shouldn't be there, or misspelling a word. For Python to work, it has to be typed EXACTLY right.

If your micro:bit shows a SyntaxError you may have forgotten simple punctuation that MicroPython needs to understand the code. Look over your code to be sure you haven't forgotten any special characters like quotation marks or colons.

Indentation is also extremely important in MicroPython. Indentation is how your program knows the order of operations. If you don’t indent, or indent too much, the micro:bit will complain about an indent error.

You can indent more by selecting the code you want to indent and pressing tab. Indent less by selecting it and pressing ‘shift tab.’

Sometimes your micro:bit just stops responding. Unplug the USB or battery cable and plug the cable back in again to power cycle your micro:bit. If that does work, try closing your code editing browser and opening it again. Make sure you've saved your code first!

Step 8: Logic Statements

Now that we’ve written code to display the temperature, Let’s write an if statement that will alert us if the temperature is over 28 degrees.

Start by using snippets to write the framework of your statement.

  • “if” starts an if statement.
  • “ei” starts an else if statement.
  • “el” starts an else statement.

We’ll add the temperature thresholds that we want to trigger certain reactions. If temp is greater than or equal to 29, do something. Else if temp is less than 28, do something else. Else, in other words, if and only if the temperature is equal to 28, do a final thing:

Display an Image

So what is the thing we want to do? We want to display an image. Go to the reference to figure out how to display images. Just like blocks, MicroPython comes with lots of built-in pictures to show on the display. For example, to make the device appear happy you type:
display.show(Image.HAPPY). 

Here’s a list of the built-in images: http://microbit-micropython.readthedocs.io/en/latest/tutorials/images.html

We’ve added a happy face to our “else” statement when the temperature is 28 degrees. Let’s add an angry face for when the temperature equal to or above 29.

Create your Own Images

You can also create your own images.

Here is an example of the code you would write for an image. This is the happy image that is already pre-coded in the micro:bit. You can replicate it by turning specific LED’s on and off using 0 for off and 9 for the highest brightness. You can see in the code there is a 5x5 grid that matches the LED light display on the micro:bit.
happy = Image("00000:"
         "09090:"
         "00000:"
         "90009:"
         "09990")

Create a Snowflake Image

Let’s create a snowflake image to represent cold.

Each LED pixel on the physical display can be set to one of ten values. If a pixel is set to 0 (zero) then it’s off. It literally has zero brightness. However, if it is set to 9 then it is at its brightest level. The values 1 to 8 represent the brightness levels between off (0) and full on (9).
snowflake = Image("50605:"
             "05650:"
             "66666:"
             "05650:"
             "50605")

display.show(snowflake)

I’ve tested it by copying it into the default sketch and uploading it to my microbit.

Let’s be honest, that doesn’t look like a snowflake at all.

Step 9: Create an Animation

Thankfully, micro:bit has an awesome feature that lets us animate images.

First, make a bunch of images that show what the snow will look like as it is falling. Name the images snowflake1, snowflake2, snowflake3, etc.
from microbit import *

snowflake1 = Image("05030:" "90200:" "01006:" "30070:" "40508") snowflake2 = Image("30900:" "05030:" "90200:" "01006:" "30070") snowflake3 = Image("40508:" "30900:" "05030:" "90200:" "01006:") snowflake4 = Image("30070:" "40508" "01020:" "00600:" "05090") snowflake5 = Image("01006:" "30070:" "40508" "01020:" "00600") snowflake6 = Image("90200:" "01006:" "30070:" "40508" "01020")

Now we’ll add them to an array named all_snowflakes.
all_snowflakes = [snowflake1, snowflake2, snowflake3, snowflake4, snowflake5, snowflake6] 

An array is a fancy way to say “list.” This is where we can list words, numbers, or images and have them appear on the LED display in order, one after the other. We put the list into a variable called snowing. That way, on the next line we can just ask the micro:bit to display.show all_snowflakes without having to re-write all of the image code again and it will show each image in the order that we listed them in the array.

To make the snowflake animation run, type “display.show(all_snowflakes)”:

I’ll set loop to true, and clear to false, since I want my snow to fall over and over again.

Setting loop to true means it will continue to loop forever, and setting clear to false means that it will not clear the LED display before starting the loop over again.

Open another browser window and paste just the snowflake code,. Download it and upload it to your micro:bit. You should see the snow falling.

Perfect. Now, if the temperature is below 28 degrees, a winter wonderland will be displayed!

Additional References/Learning Materials

We’ve gone over the basics of the Python editor. To continue learning, I’d recommend going over the getting started micro:bit tutorials found in the MicroPython reference here. If you finish those, go up one level in the reference, and you’ll find BBC’s UCL micro:bit tutorials here. These tutorials go over a number of different topics, and they also include some cool challenges.

For inspiration, you can always go to hackser.io/microbit, or search Hackster.io for tutorials using Python on the micro:bit. Happy hacking!

Step 10: Code

from microbit import *

snowflake1 = Image("05030:"
 "90200:"
 "01006:"
 "30070:"
 "40508")
snowflake2 = Image("30900:"
 "05030:"
 "90200:"
 "01006:"
 "30070")
snowflake3 = Image("40508:"
 "30900:"
 "05030:"
 "90200:"
 "01006:")
snowflake4 = Image("30070:"
 "40508"
 "01020:"
 "00600:"
 "05090")
snowflake5 = Image("01006:"
 "30070:"
 "40508"
 "01020:"
 "00600")
snowflake6 = Image("90200:"
 "01006:"
 "30070:"
 "40508"
 "01020")


all_snowflakes = [snowflake1, snowflake2, snowflake3, snowflake4, snowflake5, snowflake6] 


while True:
temp = temperature()
display.scroll(str(temp))
if temp >= 29:
display.show(Image.ANGRY)
elif temp < 28:
display.show(all_snowflakes, loop=True, clear=False)
else:
display.show(Image.HAPPY)
sleep(500)

This article written by Monica Houston comes from hackster.io.

Step 11: Contact

Share

    Recommendations

    • Arduino Contest 2019

      Arduino Contest 2019
    • Trash to Treasure

      Trash to Treasure
    • Tape Contest

      Tape Contest

    Discussions