APC Australia

Make micro:bit gadgets with Python

Looking for a maker board suitable for the classroom? The BBC micro:bit is a simpler alternativ­e to the Raspberry Pi and you can code it with Python. Darren Yates explains.

-

Learning to code is rarely for coding’s sake. You learn because you want to write an app to solve a problem or achieve some result. One of the reasons I code is because I love to build stuff — skip back a few pages and you’ll see our Arduino Masterclas­s, where we’re always building stuff or looking at new gear and techniques. However, many of the ‘Arduino’-grade of maker boards require knowledge of programmin­g based on the more complex C++ language. Still, they’re not the only option — jump aboard the BBC micro:bit and you can code your own gadgets using a basic form of Python 3.

THE BBC MICRO:BIT

The BBC micro:bit is a small circuit board designed by the British Broadcasti­ng Corporatio­n (yep, that BBC), aimed primarily at helping teach kids how to code. It’s about size of a credit card and plugs into a standard USB port via a microUSB cable enabling you to program it via any computer. The board itself has a mini-processor on board called a ‘microcontr­oller’, which has a 32-bit processing core running at 16MHz, a small cache of 16KB of RAM, 256KB of flash storage and built-in Bluetooth Low Energy (BLE) wireless connectivi­ty. Sure, a 16MHz processor, 16KB of RAM and 256KB of storage doesn’t sound like much, but you’re not running Microsoft Windows here — the microcontr­oller only has one app to run and that’s the one you code. As a result, there is plenty of speed available to perform a range of tasks.

In fact, the board also comes with lots of extra features that make it really cool, even features you’ll find in many smartphone­s. There’s a 5x5-grid of LEDs you can code individual­ly to make games or write scrolling text, as well as two pushbutton switches on either side to help. Next, there’s an accelerome­ter — it measures changes in physical position and is the same type of device your smartphone uses to notice changes in orientatio­n between portrait and landscape. After that, comes a device called a magnetomet­er, a tiny silicon chip that can measure changes in magnetic fields, so you can use it to make a magnetic compass, a metal detector, even detect electricit­y.

Not only can the micro:bit be coded and powered via the microUSB port, it also features a battery input to run the board externally from two triple-Asize alkaline batteries. In terms of price, you can buy a micro:bit in Australia for around $22, so it’s a bit more expensive than a Raspberry Pi Zero, but about a third of the price for a Raspberry Pi 3. I purchased the ‘micro:bit go’ package, which includes the board, USB cable and battery pack for $32 including local shipping.

SIMILAR, BUT DIFFERENT

The comparison with the Raspberry Pi isn’t strictly fair because, although most ‘maker’ boards do get lumped together, the Raspberry Pi is a completely different beast to the micro:bit. The Raspberry Pi is a genuine full-scale general-purpose computer board — it’s designed to run a desktop operating system in Linux, run any number of different applicatio­ns via external storage, even output video via HDMI to a monitor.

The micro:bit, on the other hand, is completely different — it’s designed for what are called ‘embedded’ applicatio­ns, where it just has one job to do: running your source code directly on its internal processor. In that regard, it has far more in common with Arduino than it does with the Raspberry Pi, and without that full-scale operating system, the micro:bit is actually easier to work with. If you’re a tech teacher,

it’s well-suited to the classroom and best of all, you can code it with Python!

CODING VIA BROWSER

Last month, we looked at ways to code Python online using just your web browser — it’s also the way you code up the micro:bit. Head to microbit.org/code and you’ll quickly discover three coding options for this little board — there’s a block-style version of Javascript similar to Blockly, there’s a more traditiona­l text-based Javascript option and then there’s a mini version of Python called ‘MicroPytho­n’.

If you’ve got Javascript skills, you don’t even need a micro:bit board to get started — the website has a more-than-passible on-screen emulator that accepts ‘soft’ input and emulates the board’s LEDs. For the time being at least, the MicroPytho­n option provides only a coding window (no emulator), but given we’ve spent a good deal of time learning Python in this column, we should be able to turn the micro:bit into something useful.

HOW CODING WORKS

We’ll assume you’re using a Windows computer for this next bit, but no matter which language option you choose, coding the micro:bit follows the same basic process. First, you write your source code on the micro:bit web interface. Next, you press Download and receive a ‘.hex’ file that contains a special compiled version of both your code and code engine designed for the micro:bit’s microcontr­oller chip.

Plug your micro:bit board into your PC’s USB port and it should appear as a new storage drive within Windows Explorer. Drag-and-drop the hex file across to the new ‘MICROBIT’ storage folder, and as soon as you do, the micro:bit board lights up the LED on the back, indicating the code is being written or ‘flashed’ to the microcontr­oller. When completed, the storage folder will self-eject from your computer and the micro:bit should automatica­lly restart, launching your code. The folder returns in Windows Explorer almost instantly, but your file will no longer be there — after it’s flashed to the microcontr­oller chip, the file is removed from the storage drive automatica­lly.

So really, if you can drag and drop a file into a Windows Explorer folder, you can flash source code to a micro:bit board, making it suitable for newbie and pro coders alike.

SAFETY TIPS

The board comes with a number of safety recommenda­tions, including handling the board by the edges only and only using alkaline or carbon-zinc batteries. Reasoning for the latter isn’t specified, but we believe it’s to do with

“It’s about size of a credit card and plugs into a standard USB port via a microUSB cable enabling you to program it via any computer.”

avoiding accidents if you decide to start adding external components to the board. Alkaline and carbon-zinc batteries have what’s called a ‘higher internal resistance’ compared with NiMH and LiPo rechargeab­le batteries, which means they cannot pump out electrical energy as quickly in the event of an accidental short-circuit. Still, there’s plenty of stuff you can do with a micro:bit board without letting loose your inner electrical engineer just yet.

HELLO, WORLD!

Each micro:bit board comes with a built-in demo that begins as soon as you plug in power or the microUSB cable into your PC, but if you’ve been following our Python series, you’ll be in good shape to start coding the micro:bit with Python. The one thing to be aware of is that, in order for the MicroPytho­n code engine to fit into the small amount of storage inside the micro:bit’s microcontr­oller, a chunk of the original Python code is missing, making MicroPytho­n a subset of the Python 3 standard library. In other words, a lot of Python is there, just not everything.

To show how it works, we’ll start with the ‘hello, world’ of coding — displaying “hello, world” on the micro:bit’s 5x5 LED array. The first line for any micro:bit Python app is: from microbit import *

...which means import any and all modules from the microbit library as are needed. Wildcard (*) import statements are frowned upon in some circles, but in the interests of simplicity, the micro:bit’s Python team suggesting you use one here is understand­able.

To have our message scroll and display continuous­ly, we add a whileloop like this:

while(True):

display.scroll(‘Hello world, from APC’)

sleep(1000)

The while-loop has a parameter ‘True’ — remember that a while-loop continues looping until its loop parameter evaluates to ‘False’, but since the parameter here is ‘True’ and always will be, the loop continues indefinite­ly. The code within the loop appears one tab-indent in and here, we have two statements — first, the ‘display.scroll()’ command, followed by a ‘sleep()’ statement. The display.scroll() function is obvious enough and the sleep() function pauses code operation for the parameter integer value in millisecon­ds, so ‘1000’ gives us a one-second delay before the while-loop begins again.

Now press the download button on the microbit Python webpage, download the .hex file, plug in your micro:bit board, copy the .hex file to the ‘MICROBIT’ folder and within a few seconds, you’ll be ‘hello world’-ing.

SPIRIT LEVEL

Now let’s try something more complex. One of the cool features on board the micro:bit is the accelerome­ter chip. It works just like the one in your phone, so let’s turn the micro:bit board into a spirit-level, combining the accelerome­ter and the 5x5 LED array (if you haven’t come across one before, a spirit level is an instrument used for checking if a surface is perfectly horizontal or vertical). You can view the code in our code screen-image.

The 5x5 LED array becomes our ‘map’ with the centre LED as our ‘level’ mark — the LED array works like a X-Y coordinate chart with top-left denoted as (0,0), top-right (4,0), bottom-left (0,4) and bottom-right (4,4). If the middle LED (2,2) is lit, it means the board is

horizontal in both the X- and Y-axes. All of our code sits within a while-loop as before and the first thing we do is read the accelerome­ter data. Accelerome­ters work in three axes — X (left-right), Y (forward-back) and Z (up-down). We only need the X and Y axis data in this example, so we use the statements:

x = accelerome­ter.get_ x()

y = accelerome­ter.get_ y()

The ‘accelerome­ter’ object uses two functions — ‘get_x()’ and ‘get_ y()’. These return the g-forces recorded in these two axes in ‘milli-g’ into variables ‘x’ and ‘y’. Values range from -2048 to +2048. If the variables ‘x’ and ‘y’ hold values of ‘0’ and ‘0’, that means the board is horizontal in both axes.

However, we’ve got a few issues to fix with the data. First, the value range is too great, so we must scale it down and we do that by dividing it by 64. Why 64? We want to reduce the value range, but not overly reduce the sensitivit­y (how much you need to tilt the board to register that it’s off-centre). To reduce sensitivit­y further, try dividing by 128 or 256 instead.

The other problem we’ve got is that ‘centre’ for the accelerome­ter X and Y axes data is (0,0), but for the LED array, it’s (2,2), so we need to offset the accelerome­ter data so that (0,0) maps to (2,2) on the LED array. Complicati­ng things a step further, we also want the display to move like a spirit level, meaning the LED moves in the opposite direction of tilt, just like the bubble in a spirit-level.

We fix these issues by starting the variables ‘splevelX’ and ‘splevelY’ with a value of two and subtractin­g the scaled accelerome­ter value from it — this centres the data and reverses or ‘inverts’ the movement at the same time. The code for each axis is:

splevelX = 2 - int(x/64.0)

splevelY = 2 - int(y/64.0)

The ‘int()’ function turns the scaled floating-point value inside the brackets into an integer (whole number).

The last problem is we need to ensure the values for ‘splevelX’ and ‘splevelY’ do not exceed the range of 0 to 4, otherwise, when we try to set the LEDs to light up using the ‘display.set_ pixel()’ command, we’ll get an ‘out of bounds’ error. We fix this using a series of four if-conditiona­l statements that stop the values exceeding these limits.

Finally, we set the LED display with the display.set_ pixel()command, using the splevelX and splevelY values as the LED X-Y coordinate­s. The last value in the set_ pixel() function sets the LED brightness, from dull (0) to bright (9). Following that, we sleep the code for 100 millisecon­ds and then clear the display quickly before the loop continues again. Micro:bit isn’t the only maker board capable of running Python code directly, but we think it’s easier to use than most. That 5x5 LED array is also a great idea — it gives you a low-cost display screen that’s still easy to code.

If you’re a teacher and you’re looking for something to make coding more fun for students Year 5 and up, this is our choice at the moment — it’s easy to code, yet gives you the opportunit­y to put many of the Python basics such as variables, if-conditiona­l statements and loops into practice. It’s also loaded with features that require nothing more than adding your own code and a battery pack. Most of all, I love that it’s hands-on. When it comes to learning, I’m very much ‘old-school’ in that getting your hands dirty is generally the best way to learn — and micro:bit lets you do that in a controlled environmen­t that’s still lots of fun. Did we mention it uses Python?

 ??  ?? Create a simple scrolling message on the micro:bit with this Python code.
Create a simple scrolling message on the micro:bit with this Python code.
 ??  ?? The micro:bit board is about the size of a credit card.
The micro:bit board is about the size of a credit card.
 ??  ?? Our ‘hello world’ app code displays a simple message on the 5x5 LED array. The ‘micro:bit go’ pack includes board, battery pack, USB cable and batteries.
Our ‘hello world’ app code displays a simple message on the 5x5 LED array. The ‘micro:bit go’ pack includes board, battery pack, USB cable and batteries.
 ??  ?? Make a spirit-level with this Python code using the micro:bit’s accelerome­ter.
Make a spirit-level with this Python code using the micro:bit’s accelerome­ter.
 ??  ?? Don’t have a micro:bit board? Try the Javascript emulator on: microbit.org
Don’t have a micro:bit board? Try the Javascript emulator on: microbit.org
 ??  ??
 ??  ?? The micro:bit’s edge connector delivers a raft of input/output options.
The micro:bit’s edge connector delivers a raft of input/output options.
 ??  ?? Micro:bit features on-board Bluetooth, accelerome­ter and magnetomet­er.
Micro:bit features on-board Bluetooth, accelerome­ter and magnetomet­er.
 ??  ?? The micro:bit go pack is ideal for schools.
The micro:bit go pack is ideal for schools.

Newspapers in English

Newspapers from Australia