First steps in Computing using the BBC micro:bit Adrian Oldknow [email protected] 28rd February 2017 0. Introduction. The BBC micro:bit is a powerful, free-standing computer of a rather specialised type. The purpose of this introductory document in the `First Steps’ series is to dig into just what you get for the very few bucks that a fully configured micro:bit costs. This is intended as general information for the interested reader to understand more about the design and features of the micro:bit. A bit like wanting to know what’s under the bonnet of your new car. The starting point is some web-searcving using Google to see what information we can find to help us. Any technological device will have a `technical specification’ to inform users what `lies under the bonnet’. So let’s start with a query: “BBC micro:bit hardware specification”. The first result is on the Micro:bit Foundation’s own site: https://www.microbit.co.uk/device.

This gives a useful introduction to the components of the micro:bit, but it does not go into much detail. The second result is on the BBC site: http://www.bbc.co.uk/mediacentre/mediapacks/microbit/specs. This is pitched at a more technologically inclined audience, but is still light on detail.

The third result is on Wikipedia: https://en.wikipedia.org/wiki/Micro_Bit .

Now we are starting to get down to the nitty-gritty. This has much more technical information – as well as links to sources of more detail. The term `Hardware’ is used to refer to the physical components of the system, which is where we’ll start. The physical design of a computing device is now often referred to as the `machine architecture’. So we find that the BBC micro:bit is a `single-board computer’.

1. The micro:bit’s hardware: CPU. What do you think the acronym `CPU’ could stand for, in the context of computing? It is a very old term called the `’ – where the instructions in a computer program are actually carried out. So the `brain’ of the micro: bit is contained in the `16 MHz 32- bit ARM Cortex-M0 ’ chip. Let’s unpick the detail conveyed here. Hz is short for the unit called the Hertz, which is a clock rate of 1 cycle per second. This is like the metronome marking for a piece of music, or the heart-rate of a human. So 16 MHz means that the micro:bit’s heart is beating 16 million times each second - wow! The `bit’ is the unit of computer storage – contracted from `Binary digIT’ – which means a single number which can be either a 1 or a 0. So in 32 bits we can store a number like: 0010 1100 0101 1101 0011 0111 0011 1001 (I put the spaces in between to make it easier to count!) Think of an ordinary whole number like 2017. How do you extract information from it? We learn to decode it as 2 thousands, 0 hundreds, 1 ten and 7 units. We use the decimal system or `base 10’. The binary number 1011 is decoded as 1 eight, 0 fours, 1 two and 1 unit = 8 + 0 + 2 + 1 = eleven. The 32-bit number above is decoded as 0 x 231 + 0 x 230 + 1 x 229 + 0 x 228 + 1 x 227 + …………. + 1 x 8 + 0 x 4 + 0 x 2 + 1 = 744,306,489 For estimates we use 210 = 1024 as roughly a thousand. So 230 is roughly a thousand million. A more convenient way of writing the same number is as: 2C5D3739. This uses the `hexadecimal’ system known as `Hex’ for short. That represents numbers in base 16. Our first 4 binary digits are 0010 which is just 2, the next 4 are 1100 which is 8+4 = 12, the next 4 are 0101 which is 4+1 = 5, the next 4 are 1101 which is 8+4+1 = 13 and so on. In base 16 we start counting 0 to 9 but then we use A for 10, B for 11 and so on up to F for 15. So that is how arrive at 2C5D3739 as the Hex equivalent of the 32-bit binary number – which we can convert here. The computer uses 2-state electronic devices to store information – which we represent by 0 or 1. `ARM’ is the name of the Cambridge-based `ARM Holdings’ company recently sold to the Japanese Softbank Group for a record £24.3bn. ARM was originally the acronym for the `Acorn RISC Machine’ developed by Acorn Computers in Cambridge, which built the original BBC microcomputer in the 1980s. The electronic engineer who set up Acorn is Hermann Hauser, originally from Austria. He was made a Fellow of the Royal Society in 2012 for his pioneering work as an entrepreneur. `RISC’ stands for `reduced instruction set computer’. A `cortex’ is a layer or region of a system, such as the `cerebral cortex’ of the brain. In this context it is just the brand name used by ARM for a particular design of solid-state integrated circuits, or `chips’. The basic component of these circuits is the transistor, which is used to amplify or switch electrical circuits. BBC’s GCSE Bitesize has a nice piece about transistors. Instead of wiring together discrete components, integrated circuits can consist of billions of transistors connected by circuits etched into the surface of a slice of semi- conducting material, such as silicon. The great rise in transistor based devices happened in California in what we now call `Silicon Valley’. Cambridge has become known as `Silicon Fen’. The picture on the right shows what is called the `die’ of an ARM Cortex chip. ARM is an unusual company in that it does not actually manufacture any chips. It produces the complex designs for chips which other companies manufacture under licence from ARM. It makes its money (annual revenue of nearly £1bn) through the licence fees paid to it by manufacturers – its product is called `intellectual property’. That is one reason for the use of the word `computer architecture’. Architects design buildings, they do not construct them! The last word to decode is `microcontroller’. This is commonly used for kind of single-board computer used to control a device such as the engine-management system for a car, or to run a mobile phone, smart television, washing machine etc. These are known as `embedded devices’ - which accounts for the generic name `’ used by ARM for its chips designed for Internet of Things (IoT) devices.

2. The micro:bit’s hardware: memory. The specification includes “256 KB , 16 KB static ram”. The `KB’ is short for `kilobyte’ and is a measure of the amount of memory. The `byte’ is not so clearly defined, though. Conventionally it is usually equal to 8 bits. Because 8 bits were enough to assign a unique number to every character on a keyboard. There is an international standardised code called ASCII, American Standard Code for Information Interchange, which assigns a numeric code to every character. But the ARM processor is a 32-bit device, which means its registers work with 32 bits. I guess that the micro:bit’s memory is organised in 8-bit bytes, but I can’t find a definitive answer! The term `flash memory’ was coined in the early 80s for a new type of `electrically erasable programmable read-only memory’ (EEPROM). I also guess that the micro:bit’s flash memory is where it stores the programs we `flash’ to it as hex files? So the micro:bit stores our programs in its memory, but what else does it need to remember? I guess that some calculations may require intermediate results to be stored temporarily. We can also create `Variables’ in the programs we write, so they must also be stored in memory. You can find out some interesting information about `static RAM’ here. `RAM’ is short for `random access memory’ – which can store data in a way which can be retrieved very quickly indeed. But this kind of memory is also `volatile’, which means it will not retain information when there is no power to the unit. We know that the micro:bit `remembers’ the last program you flashed to it, so we can rule out RAM as the place where the micro:bit stores programs.

3. The micro:bit’s hardware: Bluetooth Remember that at the moment we are just looking at the contents of a single Nordic nRF51822 chip on the micro:bit – the one called `Processor’ near the top left corner on the back of the unit. Its remaining element is the `2.4 GHz Bluetooth low energy wireless’. This is a radio transmitter and receiver using an ultra-high frequency of 2.4 gigaHerz – or 2 thousand 4 hundred million cycles per second! You may already use Bluetooth in you mobile phone to transfer music and images between it and a computer. If you have a car with a `hands-free’ for your mobile phone, you will have met the need for `pairing’, so that the car knows which mobile phone to connect to. The micro:bit is designed to be able to communicate to other devices, and Bluetooth is one way to do this. There are Apps for Apple and Android devices which you can use to develop your programs. When you have produced your `hex code’, you can then transfer it wirelessly to the flash memory in your paired micro:bit. You can find out a lot about Bluetooth and the design of the micro:bit in Martin Woolley’s blog.

4. The micro:bit’s hardware: the co-processor The Nordic chip is where the computation is carried out. As we have seen this contains (a) an ARM cortex processor, (b) memory and (c) a wireless. This remarkable device is not only tiny and incredibly powerful, it is also dirt cheap! You can buy a single one for around £3, but by the thousand this comes down to £1.50. But if you think about a car, there’s a lot more to it than just the engine. What other systems can you think of which cars need to have? If you look carefully at the back of a micro:bit you will see there is an unmarked black rectangular device on the right-hand side below the battery connector. This is called the `co-processor’. The Wiki page described this as the: `NXP/Freescale KL26Z – 48 MHz ARM Cortex-M0+ core microcontroller’. So it’s another ARM designed chip with a very fast clock-rate. Farnell sell them for £1.79. See what information you can find out about this. Wiki tells us that it: `includes a full-speed USB 2.0 On-The-Go (OTG) controller’. You are probably familiar with the term `USB’ – what do the letters stand for? You may use a USB cable to connect your micro:bit to a USB (serial) port on a computer. Suppose we want to send a large number of 8-bit `bytes’ of information from a computer. You would get information across faster if each bit had its own wire, which would make up a `parallel’ connection. But it is cheaper and simpler to use just a single wire. In that case the byte is not sent all at once, but as a series of pulses representing each bit in turn. The rate at which information can be transferred is measure in `bits per second’ by a unit called the `baud’. Can you find out what the `baud rate’ is for information sent to a micro:bit from a computer using a USB connector? As well as handling serial connections, the co-processor also controls the electrical power for the micro:bit. Wiki tells us that it `performs the voltage regulation from the USB supply (4.5-5.25V) down to the nominal 3.3 volts used by the rest of the PCB. When running on batteries this regulator is not used.’ So this is quite important information. Many microprocessors on the market (such as Crumble and ) run at 4.5V or 5V. The micro:bit has been designed to run at 3V such as supplied by 2 AAA batteries or a `coin’ battery. I made the mistake of connecting the output of a 4Tronik `crumb’ device designed for the Crumble. This outputs a signal at 4.5V which I connected to one of the pins of my micro:bit. The `PCB’ board of the micro:bit is designed to carry signals at 3V, and after a very short time I could smell burning! I had fried my first micro:bit!

5. The micro:bit’s hardware: Inputs & Outputs Unlike most computing devices there is no provision for adding a keyboard, screen or mouse. The built-in inputs are the A and B buttons on the front and the Reset button on the back. The main output device is the 5x5 array of `light emitting diodes’ LEDs on the front. There is also the MicroUSB connector on the back which can be used for serial communication with another device. At the lower side of the board there is a 23-pin edge connector which can be used to transmit digital and analog data between the micro:bit and other devices, such as the Tektronix Inventor kit and Buggy. There are also 5 large holes for use with banana or crocodile clips. Three of these are for data I/O using pins 0, 1 and 2 – the other two are for power with 0V (GND) and 3V outputs. One form of output from the micro: bit is noise! You can output mono sounds to a headphone, speakers or amplifier connected to pins 0 and GND. So a very useful and cheap add-on is a headphone jack adaptor such as this one. We have already seen that there is a Bluetooth radio transmitter and receiver. This can also function as a 2.4GHz radio transmitter and receiver.

6. The micro:bit’s hardware: sensors A powerful feature of the micro:bit is its built-in sensors. There is an NXP/Freescale (MMA8652) 3-axis accelerometer sensor via I²C-bus and an NXP/Freescale (MAG3110) 3-axis magnetometer sensor via I²C-bus (to act as a compass and metal detector). These can detect changes in orientation like a mobile phone does, as well as rapid changes such as jerks and shakes. There is also a temperature sensor and a light sensor. The values that these return are not always obvious ones! Most numbers are stored as integers in single 8-bit bytes. So they can range from 00000000 to 11111111, or 0 to 255. The micro:bit’s block editor function information for light level includes: `Gets the light level from 0 (dark) to 255 (bright)’.

So there is not a shadow of a doubt that the micro:bit is indeed terrific value for money, packing a huge bang for a very few (c£15) bucks. But, in order to unleash this power, we need to find out something about the software support for the device. Unlike most other computing devices I have ever met, there is no `operating system’ for the micro:bit – no Windows, no Android, no IoS, no Linux! If you are interested in the kind of tools which software designers and electronic engineers use with ARM microprocessors have a look at the ARM mbed compiler. This allows you to type instructions in normal text which will be compiled into the machine code using programming languages such as C, C+, C++ and C#. Not for me!!

Fortunately In order to send the code to the micro:bit we have a number of choices of so-called `higher- level’ programming editors to choose from.

7. Programming systems for the micro:bit: PXT and more got into the mobile device market with Windows 8 phones a few years ago and wanted to help App developers to produce Apps for them. Microsoft Research released free software tools for Windows 8 devices including their `Touch developer’ system. When the BBC micro:bit was being developed, they adapted their tools specifically for educational applications of the micro:bit. After the final shipment of the 1 million free micro:bits to 11-year students in the UK via their schools, the micro:bit became commercially available. The responsibility for the supply chain and future development of the micro:bit passed from the BBC to a new charity called the `micro:bit Education Foundation’. Microsoft have developed their Windows 8 `Touch Developer’ tools into a new initiative called the `Programming eXperience Toolkit’ or PXT for short. In PXT for micro:bit you have a choice to develop your micro:bit programs (aka apps) using a graphical system based on blocks, or in a JavaScript text editor. The other `First Steps’ articles explore writing programs in PXT for `control and physical computing’ and for `data-logging and modelling’. Here is a very simple computational example. This uses blocks from the `Variables’ menu to create variables called A and B and store some small numbers in them. It uses an `Add’ block from the `Math’ menu to compute variable C as the sum of A and B. It uses the `show number’ block from the `Basic’ menu to display C. No need to connect a micro:bit – the emulator runs the program just fine. If you swap to the `JavaScript’ version you get a simple text read out.

In 1970 I had to learn how to program using a simple language called BASIC. That stood for `Beginners’ All- purpose Symbolic Instruction Code’. This was a programming language written by Kemeny and Kurz, specifically for liberal arts college students at Dartmouth College in the USA to be able to learn quickly. My first computer was a Commodore Pet 8K microcomputer which ran a version of Basic called `MS Basic’ written by a very young Bill Gates, co-founder of Microsoft. In the 1980s the BBC had a very successful series of programs to introduce computing devices to families and school children. This included a powerful home computer called the BBC Micro, built by Acorn Computers in Cambridge. It had a very powerful programming language called BBC Basic, developed by Acorn. There is free demonstration version of it available here. The sample program waits for the user to type a number, which it stores in the variable A. It then calculates the square root of the number using the `SQR’ function and stores it in the variable B. Finally it displays the result on the display as a mixture of text (called `strings’) and numbers. We cannot enter even this simple program in the PXT editor for micro:bit because there is no square-root function in the `Math’ menu. This is because the variables used in PXT are all whole numbers (integers). BASIC is able to work with non-integer numbers, like √2, because it can use several bytes to store something known as a `floating-point’ number. If instead, you use Python as the programming language for a micro:bit you can use floating-point arithmetic and work with non-integer numbers.

Way back in the 1960s there was a ground-breaking US computer project at MIT called `Project MAC’ – Man And Computers. Within this a famous mathematics educator, originally from South Africa, called Seymour Papert, developed an educational programming language called `logo’. A key feature of this was its graphical output using something called `turtle geometry’. Here is a logo program to draw a square: repeat 4 [forward 10 right 90]

You experiment with this yourself here.

MIT has continued to develop Papert’s ideas and it produced a graphical programming environment called `Scratch’. Instead of typing programming commands in a text editor, you drag in programming statements in the form of blocks. Like PXT the central part of the display has a choice of types of block, such as `Motion’ or `Control’ – all colour coded. The Scratch program uses the so- called `scratch sprite’ which is a figure of a cat. The left hand of the screen is the display area where Scratch can perform. The yellow `repeat’ block is basically the same as the logo program to draw a square. The other bits are there to set up how and where the drawing is to be done. Every time you press the `space bar’, Scratch will draw a square on a clear screen.

We can do a limited amount of graphics on the micro:bit’s 5x5 LED display `screen’. In the `Led’ menu there is a `plot x y’ block which can turn on any of the 25 LEDs. This simple `square’ program uses two counted loops. The first draws the top and bottom of the square, the second draws the sides. So we are using mathematical co-ordinates, rather than the `turtle graphics’ of the logo approach. But this is not intended as a history lesson in educational computing! It is leading up to how the micro:bit, and other `embedded devices’ are designed to work on quite a different principle from earlier computer languages such as BASIC, logo, Fortran and Pascal. Instead of having just a single program whose commands are obeyed sequentially, the micro:bit is designed to be able to run several processes at the same time. Let’s go back to Scratch and see how programs can run at the same time, or `in parallel’. Here we create a second `dinosaur’ sprite who will draw a different size square in a different place on the screen when a different key is pressed. When you have created a new sprite, you can click on its image at the bottom left of the screen and enter a new set of commands. In this case the Dinosaur does its stuff when the `a’ key is pressed. Once you have set up actions for both Scratch and Dinosaur you can test the system by pressing either the space bar or the `a’ key. But what happens if you press both keys at once? The system now has both actions being performed simultaneously! But not quite. One will actually start a fraction after the other. In the example above, the program has decided that Scratch left the starting blocks just a fraction before Dinosaur. So when Dinosaur clears the screen to start drawing, Scratch had already drawn the first side of its square – so that’s why Scratch’s square has a piece missing.

Now think back to all the different control systems there are in a modern car. You press a button to control whether your window goes up or down. The moisture sensor controls when the wipers go on and off. The light intensity sensor controls when the lights are turned on and off. These could all be controlled by different micro-controllers , or a more powerful one could look after them all simultaneously (nearly). That is the principle built-in to the ARM chips. I stumbled across this explanation quite by chance! Apparently the micro:bit is designed as a `reactive system’: “The BBC micro:bit is a reactive system – it reacts continuously to external events, such as a person pressing the A button of the BBC micro:bit or shaking the device. The reaction to an event may be to perform a computation, update variables, and change the display. After the device reacts to an event, it is ready to react to the next one. If this sounds like a computer game, that’s because most computer games are reactive systems too!... The BBC micro:bit’s scheduler provides the capability to concurrently execute different code sequences, relieving us of a lot of low-level programming. In fact, scheduling is so useful that it is a part of every operating system!” So let’s test it out by creating three separate blocks of code. Pressing button A will flash one LED, press button B will flash another LED and pressing buttons A and B will flash a third LED – or will it? Try it and see. Have a look at the JavaScript version. basic.forever(() => { if (input.buttonIsPressed(Button.A)) {led.plot(0, 0)} else {led.unplot(0, 0)} basic.pause(100)} ) basic.forever(() => { if (input.buttonIsPressed(Button.B)) {led.plot(4, 4)} else {led.unplot(4, 4)} basic.pause(100)} ) basic.forever(() => { if (input.buttonIsPressed(Button.A) && input.buttonIsPressed(Button.B)) {led.plot(2, 2)} else {led.unplot(2, 2)} basic.pause(100)} )

So it appears as a sequential program but essentially we have created three independent programs which the micro:bit schedules for regular testing. Instead of needing many different micro:bits to carry out each different task, we can make one micro:bit carry them all out!

8. Getting data from the micro:bit’s sensors. In my `First steps with BBC micro:bit for control and physical computing’ I provide some ideas about using the `Radio’ commands to send data wirelessly from one micro:bit to another e.g. for remote sensing as in an alarm system. In `First steps with the BBC micro:bit for data-logging and modelling’ I describe some ways in which you can use Bluetooth to send sensed data for use with Scratch, and with the Bitty Data Logger app for Android and Apple mobile devices. Now we will have a brief look at getting data sent to a host computer via the USB cable. Remember this uses `serial’ transmission. If you look at the `… Advanced’ set of blocks you will there is a `Serial’ set, shown here. I started this piece by using the Internet to try to find out as much as I could about the micro:bit device. So I stumbled across the `ideas page’ on the micro:bit Foundation website. That took me to the Fuze page for the micro:bit which establishes 2-way wired connections between the micro:bit and your host computer using the USB cable. From there you can download and install the free Fuze Basic system. You can also download the full reference manual, and a series of 5 worksheet pdfs for the BBC micro:bit. I followed the instructions on Worksheet 1 to install the `fuzemicrobit.hex’ file on the micro:bit and to test the connection. Sheet 2 is about writing programs which output text and graphics from a Fuze Basic program to the micro:bit’s display. Sheet 3 is about writing programs which respond to the buttons A or B on the micro:bit. Sheet 4 is about writing programs which detect the various `gestures’ in the way you hold the micro:bit dynamically. The results are displayed on the Fuze output display on your computer! So we are now able to send information between the computer and the micro:bit using the USB serial cable.

You press F2 to enter the Fuze editor. The program is written in the Fuze dialect of Basic. Commands beginning `MB’ communicate with the micro:bit. MBGESTURE detects the position of the micro:bit from its accelerometers. The resulting value is a number between 0 and 11, e.g. a value of 2 corresponds to `tilting left’. Sheet 5 uses readings from the x- and y-accelerometers to control sounds. The commands to return values from the accelerometers are MBACCELX and MBACCELY. So now the floodgates really open! Fuze Basic looks and feels very much like the BBC Basic of 30+ years ago! The next program shows how we might plot the graph of a function like y = sin x in Fuze. The default colour of the graphics screen’s background is black, so we first of all cover it with a white rectangle. Then we can draw some red axes. Finally we can draw the graph in blue. The program waits until the space-bar is pressed before stopping.

So we just need to replace the y values from the sine function by those read in from the micro:bit’s sensors, and adjust the x-coordinates to correspond to times in seconds.

Here is the Data Logging program in FUZE Basic. We will use two arrays of numbers. The `t’ array holds times in seconds and the `acc’ array holds accelerations in ms-2. The loop in lines 4-9 pauses the program until the space bar on the laptop keyboard is pressed. This gives you time to get the experiment set up. In my case I have a heavy wooden model elephant, called Ellie, which hangs from the top of a door frame on a large spring. I have used Velcro to attach a micro:bit to its base. Because the micro:bit needs to be attached to the laptop I have used a long USB cable and moved my laptop to a stool close to the door frame. I can get Ellie bouncing slowly up and down before I hit the space bar. Readings are taken after a 2 second wait. The variable `tot’ holds the total number of samples, `gap’ is the interval between samples in seconds, `sec’ is the elapsed time in seconds and `g’ is the value of the acceleration due to gravity in ms-2. The loop between lines 16 and 26 reads values acx, acy and acz from the micro:bit’s three accelerometers. In order to find the magnitude of the three components we add up their squares and take the square root of the total. But the way the micro:bit’s accelerometer works means that at rest this will produce a value of 1000, since the units are in milli-g = 1/1000 of g. Lines 22 and 23 convert the three accelerometer readings into a single value to store in the `acc’ array. After all the acceleration have been logged, scaled and stored, the program waits for the space bar again before entering into graphing mode to display the results. When the graph has been displayed then the program pauses again so that you can take a screen-shot before you revert to the ordinary FUZE text screen.

The experiment worked very well indeed – but it looks as if the x-axis is just a bit below the middle of the sine-wave! I repeated the experiment with Ellie at rest, and you can see that we need to recalibrate the experiment a bit so that the rest value of the acceleration produces zero. There are extensive file handling commands in FUZE Basic, so it should be possible to create a text file with each time and acceleration value separated by a comma. Lines 56-63 create, fill and close such a text file. You need to take care either to delete, or rename, the text file before running the program again – or to change the filename in line 57 to one not already used. If you open the file in Microsoft Excel you will see a `Text Import Wizard’ dialog shown below.

The time data appears in column A and the accelerations in column B. Now we can insert a scatterplot of the data. We can also copy and paste the data into other software such as into the `Spreadsheet’ view of the free GeoGebra modelling package. In GeoGebra you can fit what are called `regression models’ to the data in any pair of columns. If we chose to use a `sine’ function to model the data we get the equation shown in the `Algebra’ view. Here we see that the amplitude is about 1.73 ms-2. The mean value is about 0.4 ms-2, and the time for a complete cycle is just around 0.5 secs.

9. Control using FUZE with a micro:bit The final example in this chapter illustrates the use of a micro:bit as a peripheral device using serial input and output to read from and write to the micro:bit’s digital and analog pins. I will use the Kitronik Inventor’s Kit for convenience. Experiment 3 in the workbook is called “Dimming an LED using a potentiometer”. An LED is connected in series with a 47Ω resistor to theGND and (analog) P2 pins of the micro:bit. A very standard first program with any microcontroller, such as an , is called “Blinky” which just flashes the LED until the program is interrupted. In FUZE Basic the program is very simple. It just writes the values 0 and 150 in turn to the analog pin 2 until Button A is pressed. So this is simple example of the program running on the PC using the micro:bit as a serial peripheral to receive an input from Button A and to provide an output to pin P2. So now we can read the analog value from the potentiometer at pin P1 and write it to pin P2. Needless to say there are equivalent mbDIGITALRead and mbDIGITALWrite commands.

You can find out more about the use of micro:bits for control and physical computing here and for data-logging and modelling here. Soon I hope to have another First Steps guide to using microPython with the micro:bit. Meantime have a lot of fun with this mighty little micro:bit.