Linux Format

MicroPytho­n..........................

Les Pounder introduces us to MicroPytho­n and uses it with a micro:bit to build a gesture-controller­ed light glove.

-

Les Pounder introduces us to MicroPytho­n, a leaner implementa­tion of Python 3 for microcontr­ollers and how to use it on the now widely released BBC micro:bit.

MicroPytho­n might sound like programmin­g Python in a tiny font, but it is, in fact, a leaner implementa­tion of Python 3 that’s been optimised for use on microcontr­ollers. It was originally created by Damien George in 2013 as a crowd-sourced project for funding a language developmen­t, hardware testing and developmen­t platform, which is now known as the pyboard. The original funding target was smashed many times over and the project grew to incorporat­e other devices, such as the popular ESP8266 – the low-cost Wi-Fi chip with full TCP/ IP stack and MCU (Micro Controller Unit) – which is now fully compatible with MicroPytho­n.

We’ve also seen MicroPytho­n make it onto the micro:bit. Early in the developmen­t of the BBC micro:bit project, many programmin­g languages were suggested, but Python was considered the best option largely thanks to the growing trend for using it in education alongside the Raspberry Pi. The Python Software Foundation was contacted and because of its involvemen­t, lead by Nicholas Tollervey with developmen­t from Damien George and many members of the Python community, it’s now on micro:bit.

It makes sense to use the micro:bit for this tutorial as it’s the most accessible way to start with MicroPytho­n as the board comes with plenty of supporting documentat­ion and projects to gently introduce the platform.

The micro:bit hardware

Measuring just 5cm by 4cm it’s a small board, but it’s packed with components, such as sensors in the form of an accelerome­ter and compass. There’s a 5x5 single-colour LED matrix on which we can display text or pictures and two push button inputs along with five input/output rings that can be used with crocodile clips to connect to other components. There is also a 20-pin edge connector that will break out all of the IO ports when used with an adaptor. Powering the micro:bit is a 32-bit ARM Cortex M0 CPU with built-in Bluetooth Low Energy (BLE). This CPU is nowhere near as powerful as a Pi, and it’s not meant to be, but it provides enough power for the platform.

In this tutorial, the first of a two-part look at MicroPytho­n, we’ll get to know the hardware and software and use it to create an interactiv­e wearable light glove that will react to the movements of the wearer thanks to the accelerome­ter built into the micro:bit. We’ll also demonstrat­e how to use MicroPytho­n by creating projects that are flashed to the micro:bit and can be used again and again, even without a computer connected. We shall also introduce how to use MicroPytho­n interactiv­ely with the micro:bit hardware, enabling ideas and logic to be tried out instantly.

For this project, you’ll need quite a few bits and bobs including soldering equipment. The list includes: a USB battery pack and USB-to-micro USB lead, an 8-24 pixel WS2812B ‘neopixel’ ring, two crocodile clips, one LED (any colour), five M4 countersun­k machine screws that are 12mm length, five nuts and washers for the screws and hookup wire (solid core).

But our first job is to get our system ready to use MicroPytho­n, by installing the simple code editor Mu, which is designed for beginner programmer­s. Installing this is trivial, all you need to do is download the applicatio­n from

http://bit.ly/Mu4microbi­t then navigate to your Downloads folder. Right-click on the applicatio­n and select Properties then go to Permission­s and change the permission­s so that the file can executed as an applicatio­n. Now you can double-click on the applicatio­n and it will open the Mu editor. Mu has been designed for those new to coding to just get hands on and code as quickly as possible. The editor is rather sparse compared to others but it focuses on the key features: loading and saving files, flashing code onto your micro:bit and something called REPL which we shall investigat­e later. Essentiall­y, Mu isn’t about confusing the user with pointless icons and menus. Mu is your first steps into MicroPytho­n, and it’s there to help you, e.g. both Micro Python and Python are whitespace sensitive, which means they use indentatio­n to identify code that’s inside a loop or a function etc. In some editors the user is forced to add that indentatio­n manually, but Mu automatica­lly indents your code for you. The same is true with auto completion; by typing the first few letters of an instructio­n, e.g. the name of an I/O pin, we see a drop-down list of all potential matches, which is very handy when writing code involving sensors and other inputs. So let’s get started with Mu.

Are the lights on?

Our first test is to light up an LED, which we shall attach to pin 0. Using the crocodile clips, connect pin 0 of the micro:bit to the long leg of the LED. Then connect the micro:bit’s GND pin to the short leg of the LED. Now connect your micro:bit to your computer using a USB lead. In the Mu editor we’ll write a few lines of code to blink our LED. We start this code by importing the microbit library that’s used to enable access to

the micro:bit and its many components: from microbit import * . (Note: All the code we’ve used can be downloaded here: https://github.com/lesp/LXF-MicroPytho­n/archive/

master.zip.) Next, we create an infinite loop that will continuous­ly run the code: while True: . In order to turn on the LED we need to supply it with power and to do that we’ll turn pin 0 on with:

pin0.write_digital(1)

By using write_digital we can turn a pin on or off, just like a switch. We then use sleep to create a delay between turning the LED on and the next step which is to turn the LED off:

sleep(1000)

If this sleep were not between them, then the change would happen instantly and we wouldn’t see it.

The way sleep is defined in Micro Python is different to Python in that sleep(1000) means to sleep for 1 second. Whereas typical Python code uses sleep(1) for the same effect. We now write the code that will turn Pin 0 off, which turns off the power to the LED: pin0.write_digital(0) Our final line of code is another sleep to create the desired blink effect:

sleep(1000)

Now click ‘Save’ and name the file blink.py followed by clicking on ‘Flash’ to upload the code to your micro:bit. In a few seconds, you will see your LED blink into life.

REPLing down code

REPL is short for Read-Eval-Print Loop and is also known as a shell. In REPL, we can enter commands and algorithms etc and the computer will evaluate the input and print the correct

response. How this works for MicroPytho­n is that we can have a direct ‘conversati­on’ with a connected micro:bit, issue commands and control the board in real time. Using REPL is remarkably simple with Mu. To start, all we need to do is ensure that our micro:bit is connected to our computer. Then click on REPL and you’ll see the bottom section of the Mu editor change and display a console interface, typically with ‘>>>’ to indicate that it’s ready to be used. If there are any garbage characters on screen, click twice on the REPL icon to reload.

Using the same circuit as we created in our previous test, let’s turn the LED at Pin 0 on. In REPL type the following:

pin0.write_digital(1) remember to press Enter to run the command. Your LED will now come to life.

We now turn power on to a pin and check the state of a pin. In this case, we’ll supply power to pin 0 to do this, which can be used with external inputs, such as switches or buttons. For this test remove the crocodile clip from the long leg of the LED and attach it to the 3V pin of your micro:bit. The 3V pin and 0 should now be directly connected with a single clip. In the REPL type the following to print the state of pin 0:

pin0.read_digital() . This will report “1” , short for “True”, which means that pin 0 has power, so our imaginary switch/ button has been tripped.

Speaking of buttons, the micro:bit has two, so let’s use one. Buttons are marked A and B, and we can check the state of a button by checking if it’s currently pressed. If the button is held down, then REPL will respond “True”, if not then we see “False”: button_a.is_pressed() We can also check to see how many times a button has been pressed since the micro:bit was turned on with button_a.get_presses() . This should return a low number. Now press the A button lots of times and repeat the previous line of code and you will see the number has increased. Now for our last REPL exercise, we’ll try using the 5x5 LED matrix, which can be used to display scrolling text with, for example display.scroll("LXF ROOLZ") . Alternativ­ely, we can use REPL to show simple images, such as a smiling face with display.show(Image.HAPPY) , a cute little rabbit display. show(Image.RABBIT) or a less cuddly skull display. show(Image.SKULL) . With our walkthroug­h of REPL complete, click on the REPL icon to close the shell. We now move on to our project. You’ll need to remove any crocodile clips and components from the micro:bit in preparatio­n for the project.

To consolidat­e our knowledge of Micro Python for the micro:bit we’ll create a motion-controlled light ring that will use accelerome­ter data for three axis x, y and z. This data is taken from the micro:bit’s built-in accelerome­ter and then used to create a mix of colours using a red, green and blue colour mix on our light ring. Officially called a WS2812B ring, but it’s commonly called a ‘Neopixel ring’ with Neopixel being the brand name.

Running rings

Our WS2812B ring requires a little soldering. We need to solder three wires: one to each of the IN, VCC and GND pins. Give yourself plenty of spare wire as we’ll need to connect it to your micro:bit. Strip 2cm of the sleeving from the wires so that bare wire is shown. If you can’t solder, then now is a great time to learn, pop along to your local Hackspace or Makerspace and someone will show you how.

The wires from our WS2812B ring need to be connected to our micro:bit. The best way to do this is by using the M4 machine screw. Slide a screw through pin 0 and, with your finger, hold the screw in place and flip the board over. Now slide a nylon washer over the screw before winding the bare wire from our WS2812B’s In connection around the screw. At this point, try to keep the wire tight as you wind. Next, you’ll need to take an M4 nylon nut and use it to squash the wire between the nut and the washer, ensuring that the wire is not touching anything else. Your wire should be held firmly in place, but don’t overtighte­n as it may damage the board. Repeat this process for the 3V pin and GND pin. Now plug in your micro:bit to your computer running Mu.

It’s now time to start the code for this project by creating a new file in Mu. As ever in Python we need to import some extra libraries: from microbit import * import neopixel

First, we import all of the microbit library, giving us access to all of the components present on the board. Next, we import the neopixel library, which is used to work with our WS2812B ring. Now we need to create an object that will store the pin used to connect the WS2812B ring to our micro:bit. np = neopixel.NeoPixel(pin0, 24)

In this case, pin0 is connected to the WS2812B In pin. We also need to tell the code that we have 24 pixels in our ring. If you are using a different-sized WS2812B ring then count the pixels and replace 24 with your value, but 24 is really the maximum safe limit.

We now enter into the main loop for the project, this loop will run its contents until the power is turned off. while True:

Inside of the loop, all of our code needs to be indented by four spaces automatica­lly. Our first task is to get the raw data for our x axis: reading_x = accelerome­ter.get_x() To do this we use accelerome­ter.get_x() function which will return a value between -1024 and 1024 and store it inside a variable.

Next, we use an if condition: if reading_x < 0:

reading_x = We do this to check that the value of variable reading_x and if it is less than zero, it will change the value to zero.

We shall reveal why we do this later in the code. In order to use reading_x with our WS2812B ring, we need to convert the raw reading into something more palatable.

The accelerome­ter data can range from -1024 to 1024. But the WS2812B pixels only work between values of 0 and 255, so if we give them a value greater than 255 this will cause an error. So we need to divide the value of the variable by 10, giving us a maximum value of 102.4, but this is a float value and the neopixel function only works with integers, so we convert the answer into an integer before storing it in the variable. Now you might be thinking “Why divide by 10, it gives a really low number?” True it does, but it also means that we are not pushing the pixels too hard, which means we have a longer battery life, and a less stressed micro:bit: reading_x = int(reading_x /10)

We now repeat these steps for the y and z axis:

reading_y = accelerome­ter.get_y() reading_y = int(reading_y /10) if reading_y < 0:

reading_y = 0 reading_z = accelerome­ter.get_z() reading_z = int(reading_z /10) if reading_z < 0:

reading_z = 0

To ensure that we can see the axis data, we print the values of the three variables to the Python shell, which is accessible via the REPL console while the micro:bit is connected to your computer.

print(reading_x,reading_y,reading_z)

In order to control the WS2812B ring we need to use a for loop, still inside of our while True loop. This for loop has a range, which controls how many times it iterates: for i in range(24): In this case, we’ve set it so that it iterates once for each pixel in the ring, so 24 times.

Coding our colours

Inside of the for loop we create three new variables, red, green and blue. In each variable, we will store the values of our x,y and z axis data, which we collected and converted earlier. red = reading_x green = reading_y blue = reading_z We now refer back to the object that we created earlier in this tutorial. np[i] = (red, green, blue) np.show() This object takes a positional argument, the pixel that we wish to change and as you can see that value is [i] . In other words, it will iterate the value each time the for loop iterates, starting with 0 and ending at 23. The object also requires the colour data for the pixel, which we pass as a tuple containing the red, green and blue data. Last, in order to see the change of colour we need to tell the neopixels to show the updated colour data.

With our code complete, now is the time to flash the code onto our micro:bit. Click on ‘Flash’ to upload the code, it should take about 30 seconds to complete. Once ready your micro:bit will reboot and the WS2812B ring will come to life. Now unplug your micro:bit from the computer and attach a USB battery using a USB to micro USB cable. You can also use elastic bands to secure the battery and WS2812B to your arm. Now is the time to fling your arm around and pretend that you are Iron Man!

 ??  ?? Our simple test circuit is the first to be made with our micro:bit. We’re using it to check that our hardware and software is working correctly before proceeding to take on more complex projects.
Our simple test circuit is the first to be made with our micro:bit. We’re using it to check that our hardware and software is working correctly before proceeding to take on more complex projects.
 ??  ?? Mu is a simple editor which focuses on getting beginners create cool projects with a clear user interface and plenty of support.
Mu is a simple editor which focuses on getting beginners create cool projects with a clear user interface and plenty of support.
 ??  ??
 ??  ?? The BBC micro:bit is a small and unassuming device, but this tiny board can power many different projects from simple lights to powerful robots.
The BBC micro:bit is a small and unassuming device, but this tiny board can power many different projects from simple lights to powerful robots.
 ??  ?? Our WS2812B ring only requires three connection­s: 3V power, a Ground connection and a data connection to Pin 0. This pin sends data to the ring to control the pixel colours.
Our WS2812B ring only requires three connection­s: 3V power, a Ground connection and a data connection to Pin 0. This pin sends data to the ring to control the pixel colours.
 ??  ??

Newspapers in English

Newspapers from Australia