Kitronik - Inventor's Kit for BBC micro:bit - Review

Table of contents

RoadTest: Kitronik - Inventor's Kit for BBC micro:bit

Author: tonygo

Creation date:

Evaluation Type: Development Boards & Tools

Did you receive all parts the manufacturer stated would be included in the package?: True

What other parts do you consider comparable to this product?: I have not been able to find a similar kit of components specifically collected together for the BBC Micro:Bit. Three other suppliers have designed Micro:Bit to breadboard connectors: Adafruit, Proto-Pic and Pimoroni. You would have to buy the other components separately and there would be no instructions.

What were the biggest problems encountered?: Some of the downloadable files did not work as expected. The specified program editors only work while online. (Others are available which work offline and have additional, helpful extensions.) Provides more emphasis on the electronics than the coding.

Detailed Review:

The Inventor’s Kit describes itself as, “The simple way to learn about creating circuits and code,” and is intended either as an add-on for those who already own/use a BBC Micro:Bit and wish to move on to Physical Computing, or for others as an introduction to computer coding and their first introduction to writing code and building circuits. Pupils find blinking lights so much more interesting than editing text strings!

I’m hoping that the kit will supply sufficient support to allow a non-coding parent and child, with just school experience with Scratch, to progress in an enjoyable way to creating their own circuits and writing the code to drive them in their own project ideas. I would hope they would be confident in having moved from Block code to a higher-level text-based language. Python is currently the most popular in secondary schools in the UK and I hope this kit will provide a sound introduction to the language.

On opening the box from Element 14 I found the expected kit and a couple of bonus items: a new BBC Micro:Bit and a USB cable. Thank you, Randy and Element 14. These additional items are essential to make use of the Inventor’s Kit. The kit is also available with these items and a battery pack included at additional cost.

image

On opening the kit, I found that the contents were very well protected, with bubble-wrap at the bottom of the box and the instruction booklet at the top. The booklet is version 1.5 with major changes from version 1.1. The components were in small plastic bags to keep them neat and tidy.

My first task was to arrange the kit components and take a photograph.image

The following items are included in the kit:

1 x Base Plate with 4 columns

1 x Potentiometer & Finger Adjust Spindle.

1 x Sticky Fixer for Battery Pack.

1 x Small Prototype Breadboard.

1 x Terminal Connector.

4 x Push Switch.

1 x Motor.

1 x Transistor.

2 x Red 5mm LED.

2 x Orange 5mm LED.

2 x Yellow 5mm LED.

2 x Green 5mm LED.

1 x RGB 5mm LED.

1 x Fan Blade.

5 x 2.2KΩ Resistor.

5 x 10KΩ Resistor.

5 x 47Ω Resistor.

1 x Edge Connector Breakout Board for BBC micro:bit.

1 x Miniature LDR.

10 x Male to Male Jumper Wires.

10 x Male to Female Jumper Wires.

1 x 470uF Electrolytic Capacitor.

1 x Piezo Element Buzzer.

2 x Pan Head M3 Machine Screw.

 

I'm not sure what the capacitor will be used for and the only item not in the kit that I would add is a single digit 7-segment LED display.

Many of these items can be purchased separately from many sources, including Element 14 and Kitronik. The Edge connector Breakout Board for the BBC Micro:bit has had little competition until recently. Alternative connectors, which require some soldering, are produced by Proto-Pic.co.uk, Pimoroni.com and Adafruit.com. These plug directly into the breadboard and have the pins arranged in numerical order. The purchaser has to solder the pins to the board. The Micro:bit is held at right angles to the breadboard. The Pimoroni version does not connect all the pins. It leaves out those which are also used to drive the 25 LED display on the face of the Micro:bit. Many users will find that purchasing the complete kit is cheaper and easier than sourcing the items individually.

I immediately noticed that the black base plate has undergone a major upgrade. It now has indented areas for the breadboard and an optional battery pack. There are now four pillars to better support the connector and no longer any need to put screws through from the bottom of the board or stick on feet.

This is a major improvement and supports the connector much better than on the original boards.

Assembly of the prototyping plate was fairly straight forward. The exploded diagram shows clearly how the components fit together and you are reminded that the breadboard is self-adhesive and should be fitted into its recess with column numbered 1 at the left-hand end. Fixing the connector was more tricky. The underside has a green plastic foam layer at the front. You need to take special care when inserting the screws not to unstick this insulating layer while fixing the connector to the posts. (Probably quite difficult for a child to do on their own and this kit is sold for students aged 10+.)

image

image

With the board built I inserted the Micro:Bit into the slot. It needs a very firm push to seat it properly. I then checked to see how much more secure the new version of the board was than the original. When using the board for the experiments you will need to close the switches. It is probably best to pinch the buttons with a supporting finger under the edge of the board and a thumb on top. This will not flex the connector as much as just pressing the buttons from the top. Some students will treat the setup quite forcefully, just pushing down on the buttons, putting strain on the soldered connections. If this is a worry then I suggest cutting a rubber/eraser and placing it under the Micro:Bit for additional support. Remember to allow for the lower surface in the battery pack indent when measuring the height of the support. See photographs. The new base plate is really much better than the original.

image

image

If this your first Micro:bit do not miss out on powering it up via the USB cable and running the program installed in it.

On comparing the software used in the instruction book I noted that original, legacy software, no longer supported, has been dropped in favour of the current Microsoft PXT Block editor and the Microsoft PXT Javascript editor. This is also a major improvement as the previously used Microsoft Touch Develop Editor was very difficult to use. (I gave up on it after battling away for a couple of hours, getting nowhere.) Python, also currently available, with several different editors, is not used in the instruction book.

Kitronik support a website with updates to their kits.

https://www.kitronik.co.uk/5603-inventors-kit-for-the-bbc-microbit.html will take you to the appropriate page. The experiments are repeated here with photographs, videos and corrections to earlier additions of the kit’s instruction book. There are also two additional experiments, not included in the book. This looks to be a very useful addition to the tutorial booklet. 

The book then provides the reader with pictures to help identify the various electronic components included in the kit. The resistors are shown with their coloured bands and are 47, 2.2K and 10K Ohms. I felt that an educational opportunity was missed at this point. It was an ideal opportunity to explain the colour code used to show the value of a resistor. This is a useful site if you do not know how the code works. https://neurophysics.ucsd.edu/courses/physics_120/resistorcharts.pdf

Now might be a good time to write the values on the paper holders at the edge of the resistor legs.

I checked the kit and all the parts were correct. The following pages explained how a breadboard is connected up internally and how Jumper Wires are used to join up components. A diagram shows how the Micro:Bit is connected to the USB port of a laptop.

To use the kit you have to write scripts or programs to run on the Micro:Bit. Page 8 explains how to access the editors used to develop the code. First time Micro:bit users are advised to visit www.kitronik.co.uk/microbit

This is really an advertising page for Kitronik’s Micro:bit products. More useful is a link just below the top picture which takes you here:

https://www.kitronik.co.uk/blog/bbc-microbit-kitronik-university/

This is really helpful if you are just beginning with a Micro:Bit.

I suggest you click on these two:

The Five Minute microbit Guide.

The Parent's Complete Guide To The BBC micro:bit

The second can be downloaded as a pdf for later reference.

Time to get reading so I’ll pack up the kit. At this point I notice that the box is really useful. It will hold all the parts safely until next time and there is even room to hold the prototyping board with Micro:Bit and components fitted to the breadboard.

The software

One problem here is that both the current editors require internet access to work. This may restrict where you will be able to program your Micro:Bit. You have a choice from two compilers. http://microbit.org/code/ to see them. A link at the bottom of the screen gives access to the legacy editors, which are no longer supported, but were used in the earlier versions of the kit. They may soon be withdrawn.

The first is a dual editor holding both the Microsoft PXT Block and Microsoft PXT JavaScript editors and the second is a Python editor. The booklet only provides instructions for the Microsoft editor. This was a major disappointment as Python is a language widely used in education in the UK and elsewhere for 11-year-olds upwards. (I will come back to this later.)

The first six experiments use the Block version of the Microsoft editor.

It is always good practice to EJECT the MICROBIT DRIVE before pulling out the USB cable from your computer.

Experiment # 1  SAY “HELLO” TO THE BBC micro:bit

https://www.kitronik.co.uk/blog/inventors-kit-experiment-1-help

This is very similar to Scratch, used in many primary schools, and my granddaughter, nine years old, quickly picked up how to find and join the blocks together in the slightly different screen environment.

image

At the bottom of the screen is a grey outlined box where you can give your program a name. We used ‘one’ for the first experiment and quickly built the program from the picture in the book. Once you have finished the block program you can try it out on the simulator at the left of the screen. Just click the mouse on the A and B Buttons to test it.

Now you need to compile the code into a form that the Micro:Bit can recognise and transfer it to the Micro:Bit. To do this you click on the DOWNLOAD button at the bottom left of the screen and this writes a file called ‘microbit-one.hex’ in your Download folder. (I’m using Windows 10 computers.) To transfer this file to the Micro:Bit you first connect it to a USB port with the cable. At this point a new drive appears called MICROBIT. You drag the newly created ‘microbit-one.hex’ file from the Downloads folder and drop it on the MICROBIT drive. A transferring box appears on the screen showing the progress and a yellow LED on the back of the Micro:Bit flashes. When the flashing stops your new program is running in the Micro:Bit. Gently press the A and B buttons in turn to test that it works as described.

You can also use the ‘microbit-one.hex’ file to reload the program back into the editor for a second session. You just drag the ‘microbit-one.hex’ file into the editor window.

Before finishing I suggest that you click on the JavaScript button at the top of the screen to get some idea of what the alternative code looks like. You will be using JavaScript for the later experiments in the book so it helps in understanding syntax and the use of brackets. It may look quiet daunting to a young person who has only used blocks before.

image

 

 

 

At this point you start to build circuits and put push switches in parallel to the buttons. Push switches like these are quite difficult to insert into a breadboard or stripboard. A pair of narrow nosed pliers is very useful in straightening the legs and pointing them straight down. The legs need to be at the top and bottom when they are inserted, as the internal connection when pressed is from side to side. The jumper wires are much easier to fit. Rerunning the program, by pressing the button on the underside of the microbit allows you to use any of the four buttons to control the display.

At this point I thought I would take a look at the Python code for the same experiment. On the Exp#1 web page there is the opportunity to download the appropriate .hex file. I clicked on the one on the Python line and downloaded a file called ‘exp-1-makecode-pxt.zip’ (232KB). This is not looking right! makecode-pxt???

Since this is a .zip file the user needs first to extract the unzipped contents and obtain a full-sized file. I did this and got a file called ‘microbit-Inventors-Kit-experiment-1-.hex’. The website tells you to drag-n-drop the file onto the editor. I dropped it onto the Python editor and nothing happened. It is the file for the other editor, not Python.

At this point I thought about a 10 or 11 year old, new to coding, having to extract a file from a downloaded zip file, and drop it on the editor. This is a bit too complicated to do without help initially – and then it does not work! The programs are short. You learn by doing. Typing in the code will improve your keyboard skills and correcting typos to fix code is an essential skill. Please provide a listing of the Python code on the website.

I then looked at a Python download for a later experiment to see if that worked better. I tried the compass experiment, number 8. That worked properly.

Looking at the circuit I notice that there are internal pull-up resistors on the buttons. Their purpose is not explained.

Experiment # 2    USING AN LDR & ANALOG INPUTS

https://www.kitronik.co.uk/blog/experiment-2-using-an-ldr-analog-inputs/

The circuit is easy to build and the booklet explains the concepts well. The Block program is easy to build and gave no trouble. The ambient light level may be a problem. If the display stays showing a moon in low light levels you may need a torch to switch on the sun. In bright light it may be difficult to see the moon display. Alternately, you could change the threshold level, 512, in the IF block.

At this point I successfully downloaded the Python version of the code and compared the three versions.

image

image

image

The Blocks version is easy to follow if you have used Scratch. The Python version is very similar in layout with the display definitions first, followed by a simply laid out IF-THEN-ELSE. This is also fairly easy to understand. However, the Javascript version has so much extra, difficult to type and pretty unintelligible punctuation that it is quite confusing. Look in particular at line 2:

      basic.forever(() => {     

Rather difficult to get your head round if you are 10/11 and have never seen a text program before.

Experiment # 3    DIMMING AN LED USING A POTENTIOMETER

https://www.kitronik.co.uk/blog/inventors-kit-experiment-3-further-help

This experiment introduces many (possibly too many) new ideas: connecting up an LED, connecting up a potentiometer, analog and digital input/output, Pulse Width Modulation. Many education concepts are missed. The difference between digital signals (binary – 1 or 0, True or False) and analogue signals (continuously variable) are very important. When we use an analog to digital converter, A/D, we get an approximation of the original signal. See: https://learn.sparkfun.com/tutorials/analog-vs-digital if you want more information.

“Why do we need the resistor?”

“Why that resistor (yellow, purple, black, gold = 47 ohms) and not one of the others?”

These are important questions and I would have expected them to be addressed. (To restrict the current so that the LED and the processor chip are not burned out. If the resistance is too high the LED will be too dim.)

PWM is explained in the next experiment and  voltage division, as in the potentiometer, was explained in the previous experiment.

That said, the circuit is easy to build and the program easy to enter from the block diagram. Just make sure the LED is the right way around. The Python .hex file works.

I usually connect up the potentiometer with 0 and 3 volts the other way around so that higher values are in the clockwise direction, like a volume knob.

With my teacher's hat on, I think there is too much covered in this one experiment. I would have covered the digital I/O separately from the analogue I/O.

At this point, and to consolidate the learning, you could try the following extensions:

  1. Write a program to make the LED blink on/off every half second. (Use a BASIC – PAUSE block to slow things down.)
  2. Add an extra LED (and 47-ohm resistor) to pin 12. Change the program to blink them both so that when the first is ON the other is OFF and when the first is OFF the other is ON.
  3. Control the blinking with the switch. Button UP first ON and Button DOWN second LED ON. It should show only RED or GREEN.

 

Experiment # 4  USING A TRANSISTOR TO DRIVE A MOTOR

https://www.kitronik.co.uk/blog/experiment-4-using-a-transistor-to-drive-a-motor/

Here the downloaded Python file is called ‘Experiment-4-MicroPython-Code.jsz’ and does not work with the current Python editor or the legacy Python editor when dropped.

This experiment works well. The Block code is easy to construct but you need more care with building the circuit. The terminal connector needs a small screwdriver to connect the motor leads to the connector. Take care to get the coloured motor wires the right way around. The connector makes it difficult to see which column of holes the legs fit into. I found it useful to splay out the legs of the transistor to span 5 holes before pushing it into the breadboard. Make sure the transistor has its curved edge nearest to  the Micro:bit. You will need this circuit for the next experiment so do not dismantle once this experiment has finished. A small blob of Blu Tack on the back of the motor stops it wandering about.

Pulse Width Modulation (PWM) is explained in the text. Experiment worked well.

Experiment # 5    USING THE ACCELEROMETER TO CONTROL MOTOR SPEED

https://www.kitronik.co.uk/blog/inventors-kit-experiment-5-further-help

This uses the previous circuit without modification. The downloaded Python .hex file works in the current Python editor. (Drag and drop)

The block code is very easily built and is very responsive. Impressive! Try changing the y to an x and tilting sideways.

The accelerometer is well explained in the booklet.

Experiment # 6  SETTING THE TONE WITH A PIEZO BUZZER

https://www.kitronik.co.uk/blog/inventors-kit-experiment-6-help

My wife hates the sound of these devices when making ‘MUSIC’. Be warned. Kids usually like the sound.

The circuit and block code are easy to setup. Thankfully, with the buzzer, the sound is not very loud.

Use of PWM to make square wave notes is explained.

If you edit the Middle C on button B you get a piano keyboard on the screen. Very nice interface!

image

The Python code works but only for Button A. The Microsoft editor wins here.

image

Extensions: You could extend the program to play a tune of your own making. Google “Simple tunes as sheet music” and convert a score to a computer program.

===========================================================================

At this point the book switches to the Javascript editor and suggests you can find more information at:

  1. www.kitronik.co.uk/javascript and pxt.microbit.org/javascript but the latter does not appear to work.

Experiment # 7  WIND POWER

https://www.kitronik.co.uk/blog/experiment-7-wind-power

If you have earlier versions of the booklet, before version 1.5, you need to correct the errata. The necessary changes are shown on this page. Take care to wire the motor the other way around so that the red motor wire goes to GND, 0 volts.

image

The code is more difficult to type in than building a Block program. Take care with the capital letters and special symbols. If you click the Block button at the top of the screen you should see the simpler version if you have typed it in correctly. The Python download works correctly.

image

Using the motor to generate a voltage and current is explained and the programs worked well.

As extensions you could use the same program but measure the output from the centre pin of the potentiometer as you turn the knob, with the outside pins connected to 3 and 0 volts, as in experiment 3, or used the LDR and a 10K ohm resistor as in experiment 2. Try using a torch to increase the light.

Experiment # 8  MAKING A GAME USING THE COMPASS

https://www.kitronik.co.uk/blog/inventors-kit-experiment-8-further-help

This one is great fun. The circuit is very easy to build. Make sure to check that the LED is the right way around, flat edge and short leg is connected to GND.

You need either a long USB cable or a battery pack for this experiment. To calibrate the compass chip, you have to turn and twist the MicroBit in all directions until you get a ring of lit LEDs round the edge of the display. Only when a smiley face appears on the screen is it properly calibrated and the game can begin.

This is a long program to type in and I’m sure there will be mistakes and typos. Take care with the indents and capital letters. If you get stuck you can download the .hex files from the web page and drop them into the editor or onto the Micro:bit. They both work properly.

image

Experiment # 9 CAPACITOR CHARGE CIRCUIT

https://www.kitronik.co.uk/blog/inventors-kit-experiment-9-help

This is a complicated circuit but clearly laid out on the diagram and is quite easy to build. Check carefully the components which must be the correct way around, such as the capacitor, LEDs and potentiometer. It is easier to turn the pot if it is moved closer to the bottom edge of the board.

Use the copy and paste keys (CTRL+C) and (CTRL+V) to speed up program entry. The program works well but you might want to watch the video before trying it yourself. If you download the .hex files the Python one works properly but the Javascript version has errors. In the last two blocks of code there are two P8 lines. The last lines should read P12. What is happening electronically to the capacitor is explained so that you can understand the significance of the LED lights.

image

Experiment # 10  USING AN RGB LED

https://www.kitronik.co.uk/blog/inventors-kit-experiment-10-help

(Version 1.1 of the book confused the analog write pins on page 53. Check the errata.)

Here we are using three pull-down resistors to hold pins P8, P12 and P16 at 0 volts until the switches are closed connecting them to 3.3 volts. When closed the value of the pins change from 0 to 1, False to True. Pins P0, P1 and P2 are set to PWM mode to drive the brightness of the Red, Green and Blue LEDs held close together in the common cathode RGB LED.

This circuit is easy to build. The longest leg of the RGB LED is the common cathode and is connected to the GND rail of the breadboard. You need to spread out the legs before pushing the RGB LED into the breadboard. Make sure you use the correct value resistors.

Both download .hex files work correctly.

The back cover of the book illustrates the uses of the GPIO pins and which are allocated to special functions. Notice that several of the pins are devoted to driving the 25 LEDS on the face of the Micro:bit and if you need to use the display in your program for feedback they cannot be used for other things.

Here we have reached the end of the experiments in the book. The two addition examples on the website both use Blocky programming and second illustrates how you can use a single 47-ohm resistor to protect two LEDs. (Put the single resistor between both the cathode legs and GND.)

https://www.kitronik.co.uk/blog/inventors-kit-experiment-11  Traffic lights

https://www.kitronik.co.uk/blog/inventors-kit-experiment-12  Random dice

I would hope that at this point users of the kit would be ready to start designing circuits and writing code for their own projects. If you are using a text-based language and you are not an experienced keyboard user you will make many typos and mistakes which could be errors of syntax or logic. I thought I would see how the two editors cope with faulty code. Just a simple program to flash an LED 5 times should provide an insight. For the circuit we just need to connect the LED via a 47-ohm resistor from 2 to GND.

P2 => 47-ohm resistor => GND    as the circuit for experiment 3

I tried the JavaScript editor first. Help can be found here: https://makecode.microbit.org/javascript

image

Note: for 5 blinks you compare index with <= 4       ( 0, 1, 2, 3, 4)  This worked properly.

I then edited a few mistakes to see what happened.

image

At or near the mistake a red wriggly underline appears and if you point the mouse at the underline you get some help.

image

Here a semicolon has been replaced with a comma. Two underlines appear. The first is not very helpful but the second, is correct but not near the error.

image

Conclusion: some help but could be better.

If I try to create a .hex file I get this:

image

The .hex file is still created but it does not run. No error message appears on the LED display.

Next I tried the Python editor. Help can be found by pressing the Help button. Some of the facilities listed in the document appear to have been disabled.

image

This works properly. It still counts from 0 to 4 to get the 5 blinks!

If I leave out the underscore on line 4 no error is flagged in the editor and I can create a new .hex file. On transfer I get an error message on the 25 LED display which begins," Error in line 4 ……". The rest flies past too quickly to read easily. Not very helpful.

A guide to Micropython, as used in the editor, can be found here: http://microbit.org/guide/python/

Where I found this:

Projects related to MicroPython on the BBC micro:bit include:

  • Mu - a simple code editor for kids, teachers and beginner programmers. Probably the easiest way for people to program MicroPython on the BBC micro:bit. This looked promising.

At this point I searched Google for a simple link to Mu and how to down load it. The website is here: https://codewith.mu/

It has downloads for Windows, OSX and Linux.

I tried the Windows version on my current Windows 10 Desktop, Laptop and on a very old Samsung NC10 Netbook, originally Windows XP but after a small RAM upgrade still runs Windows 7. It works perfectly on all 3 and installation was simple.

 

image

This editor has several advantages over the previous one:

  1. It works offline, so you are not tied to an internet connection
  2. Directly download your code with the FLASH button to the Micro:bit without having to create a .hex file and drag it to the MICROBIT drive.
  3. Save and load your Python code in a .py file. Which you can transfer to other Python editors for printing.
  4. It has a REPL - "A Read–Eval–Print Loop (REPL), also known as an interactive top level or language shell, is a simple, interactive computer programming environment that takes single user inputs (i.e. single expressions), evaluates them, and returns the result to the user; a program written in a REPL environment is executed piecewise." This also allows the Micro:bit to send messages and printed output to a separate window on your controlling computer. You turn it on by a click on the Repl button at the top.
  5. Error messages appear in the REPL window where they are easier to read than on the LED display.
  6. You can now use the GPIO pins for your projects which you previously had to use for the 25 LED display.
  7. Insert print statements in the code to print the value of variables to help de-bug logical errors. See "print(i)" in the code below.

image

Trying it with the same mistake

image

You can now clearly see the error message at the bottom of the screen - so much easier than the scrolling LED message. This seems to be a great improvement over the previous Python editor. Note that the script started to execute, two lines were printed, but died on line 5.

The Raspberry Pi Foundation has been supporting the development of Mu for the BBC Micro:bit and a more powerful version of the Mu editor is available from:

https://learn.adafruit.com/welcome-to-circuitpython?view=all#installing-mu-editor  (This is also used to program more powerful educational boards such as the Itsy Bitsy M0, which plugs directly into a breadboard.)

image

(This one needs Python 3 to be installed first - remember to tick the box so that it is included in PATH.)

Now that we have a suitable Python editor I thought that I would return to "retired teacher mode" and try to write a few additional educational projects using parts from the kit and Python.

Educational theories about teaching coding are undergoing an update at the moment with the PRIMM model (Predict, Run, Investigate, Modify and Make).

You can read more at https://blogs.kcl.ac.uk/cser/2017/02/20/exploring-pedagogies-for-teaching-programming-in-school/

  1. Pupils are given a working program script to read through and Predict what it does.
  2. They then Run the code to test their prediction.
  3. They Investigate the code, line by line, to see how it works, paying particular attention to the new parts - possibly adding additional comments.
  4. They then Modify the code to show that they understand how it works.
  5. Finally they Make a new project using the new idea they have been working on.

If you are new to programming in Python then I suggest you follow this methodology in the following exercises.. 

====================================================================

LEARN MicroPython with Kitronik Inventor’s Kit and Mu editor

 

This guide assumes that the reader has followed the instructions for all the experiments in the booklet and is familiar with the components and how to connect them together using a breadboard. The reader should also understand the concepts of digital and analogue I/O, and of loops to repeat the execution of blocks of code.

 

http://microbit-micropython.readthedocs.io/en/latest/

This website provides the full documentation for MicroPython with the BBC micro:bit. Make it your first place to go if you need more information. Please read the first page, especially the warning about errors as you learn.

 

Ex # 1 - A single LED on Pin 16

 

Carefully connect a RED LED to pin 16 with a 47-ohm resistor (yellow, purple, black, gold) and then the short leg to the GND rail. Connect the GND rail to GND on the Micro:bit. Do this in row 29 of the breadboard.

 

Look carefully at this code and predict what it will do. Write this down or discuss it with a partner. There is an LED attached to pin 16 of the Micro:bit. The first line is always needed when using a micro:bit with the editor. (It loads microbit specific code.) Comments, after the hash character, #, are only to help people. They are very useful when you, and/or someone else, come back to code at a later date and try to understand how it works. I encourage you to use them in your scripts.

 

from microbit import *  # This is a comment

print("\nSTART")        # Print with a new line in REPL window

pin16.write_digital(1)  # Digital output - LED ON

print("ON")

sleep(1000)             # 1 second delay = 1000 ms

pin16.write_digital(0)  # Digital output - LED - OFF

print("OFF")

sleep(1000)

display.scroll("Nearly done.") # Scroll on micro:bit

print("\nFinished")

 

Using the Mu editor type in the script/program (or copy and paste it). Connect your Micro:bit to the computer with the USB cable. Execute/RUN the script by clicking on the FLASH button at the top of the editor window. Click on the REPL button and run the script again.

 

If you get an error message on the Micro:bit, or in the REPL window, check that you have entered the program correctly, fix the error and run it again until it works.

 

  1. What do the print statements do?
  2. What does the \n in a print statement do?
  3. What does a sleep(1000) statement do? Try changing the number and running the program again.
  4. Which statement turns the LED ON? Which statement turns it OFF? (A digital signal is binary, one of only 2 values: 1 or 0, True or False.)
  5. Change the program so that it scrolls your name on the line below START, and prints it at the end of the program, before Finished. Leave 2 blank lines above Finished.
  6. Add extra lines to the program so that the LED flashes three times.
  7. Make it flash the LED slower/faster.
  8. Save your script calling it Ex1A

 

Add a green LED and resistor in the same way connected to Pin 14 in row 24 of the breadboard.

 

  1. Write a program to flash the green LED 5 times and print your name each time it flashes.
  2. Make it flash faster each time.

 

Ex 2 - Loop, LEDs, switches, button and potentiometer

 

Add a yellow LED (and resistor) in row 26 connected to pin 15.

Connect the potentiometer to GND, pin2 and 3V.

Connect 2 switches, with pull-down 10Kohm resistors, to pins 0 and 1

Connect the 3V rail.

 

from microbit import * # import microbit library

# LEDs on pins 14, 15 & 16

# Colours:      G   Y    R

# Potentiometer on 2

# Switches with 10K pull down resistors on pins 0 and 1

print("\nSTART")        # Print with a new line in REPL window

while True:                     # Start of endless loop

    left = pin0.read_digital()  # Read left switch – digital input

    if left == 1:               # If it is pressed

        pin14.write_digital(1)  # LED ON

    else:                       # If not pressed

        pin14.write_digital(0)  # LED OFF – digital output

    right = pin1.read_digital() # Read right switch

    if right == 1:

        pin16.write_digital(1)

    else:

        pin16.write_digital(0)

    sleep(100)

    pot = pin2.read_analog()    # Read voltage on potentiometer

    pin15.write_analog(pot)     # Set PWM on LED - adjust brightness

    print(left, "\t", right, "\t", pot)  # Print with tabbed columns

    if button_a.is_pressed() == True: # Check button A

        break                   # Break out of loop

 

# Tidy up after leaving loop – always good practice    

pin15.write_analog(0)   #Turn off all LEDs

pin15.write_digital(0)

pin16.write_digital(0)

pin14.write_digital(0)

print("\nFinished\n")

 

Read through the script carefully and decide what you think it does. Discuss with a colleague or write down a description.

 

Run the program and gently press each of the switches, one at a time or together, and turn the potentiometer knob. Finally gently squeeze button A on the Micro:bit.

 

Which lines use analogue input or output?

What variable names are used? What values do they hold?

 

Modify the program so that the LEDs are controlled by the buttons A and B and it halts if the left switch is closed.

 

  1. Write a program to vary the brightness of the RED and GREEN LEDs with the potentiometer so that as one gets brighter the other gets dimmer. If the RED is full ON the GREEN is full OFF and both are at half power in the middle setting of the pot. (Hint: 1023 - ???)
  2. Halt the program when BOTH switches are closed.

 

Ex 3 – Counting and controlling loops

 

There are no changes to the circuit/breadboard for this exercise.

 

from microbit import *

# Red LED on pin16 (with 47-ohm resistor)

# Switch with 10K pull down resistor on pin0

# Define a small procedure to call later

def blink(delay):

    pin16.write_digital(1)

    sleep(delay)

    pin16.write_digital(0)

    sleep(delay)

 

#==== MAIN ====

wait = 800  # sleep time in ms

print("\nSTART")

print("Loop 1 - Count up - long method")

count = 0

while count < 5:

    print(count)

    blink(wait)

    count = count + 1

print("Done\n")

 

print("Loop 2 - Count up with FOR - full")

for c in range(-2, 3, 1): #(start, stop, step)

    print(c)

    blink(wait)

print("Done\n")

 

print("Loop 3 - Count up with FOR - simple")

for c in range(5):

    print(c)

    blink(wait)

print("Done\n")

 

print("Loop 4 - Switch controlled")

print("Hold down switch to stop looping")

print("No count - just blinking")

running = True

while running:

    blink(wait)

    switch_state = pin0.read_digital()

    if switch_state == 1:

        running = False

print("Done\n")

 

print("Finished")

 

Read through the script and write down all the printed output you expect it to produce.

Run the program and check your predictions against the output in the REPL window. (You can scroll it up and down with a mouse wheel.) Investigate any deviations between your prediction and the actual output.

 

What does the blink() procedure do? Where is it called? I hope you can see how much more compact the program is when using a procedure. “wait” is a value passed to the procedure and picked up by the internal variable, “delay”, for use within the procedure.

‘wait’ is called an argument, while ‘delay’ is called a parameter.

 

https://www.google.co.uk/search?dcr=0&source=hp&ei=HiUEW5ujHob2kwXMuK-oCA&q=python+arguments+vs+parameters&oq=Python+arguments&gs_l=psy-ab.1.8.0l10.4296.9518.0.14724.16.10.0.6.6.0.277.1558.0j9j1.10.0....0...1c.1.64.psy-ab..0.16.1885...0i131k1.0.Y-Yq1eqwdZw May help.

 

Write loops to produce the following lists of numbers: (Blinking not needed.)

a) 0, 1, 2 … 9

b) 5, 4, 3, 2, 1, 0

c) -12 to +12 in fours

d) 4, 2, 0, -2, -4

e) 25 to -25 in fives

f) 9 to -9 in threes

 

Ex 4 - Using a pointer or index in a list

 

Add two more LEDs (with resistors)

Yellow in row 22, connected to pin 13

Red in row 20, connected to pin 12

 

In this program the variable ‘i’ is used to point to pins in the LIST of pins.

For example: pins[2] is pin13, connected to the YELLOW LED.

(Sorry for the ‘i’. I first programmed with Fortran IV back in ’68 - Integer variable names started with the letters I, J, … N.)

 

from microbit import *

# LEDs on pins 12, 13, 14, 15 & 16 (with 47-ohm resistors)

pins = [pin12, pin13, pin14, pin15, pin16] # List of pins

# Colours R      Y      G      Y      R

def clear():

    for i in range(5):

        pins[i].write_digital(0)

def fill():

    for i in range(5):

        pins[i].write_digital(1)

#==== MAIN ====

print("\nSTART")

for i in range(5):

    print(i)

    pins[i].write_digital(1)

    sleep(1000)

    pins[i].write_digital(0)

    sleep(1000)

 

sleep(800)

clear()

fill()

sleep(500)

clear()

 

Predict what you think this program does and add suitable comments.

Run the program and adjust the comments as necessary.

Add code to move the lit LED back to the left and off again.

 

Write programs to sequence the following:

  1. Run the lit LED back and forth across the 5 LEDs. Stop, with all LEDs OFF, when both buttons, or switches, are pressed together.
  2. Flash the green LED twice, then the yellows twice, reds twice, yellows twice, green twice and all off. Repeat 3 times.
  3. Improve your code by using a procedure.

 

Ex5 - Potentiometer and LED meter

 

image

 

No changes to the circuit on the breadboard. Uses 5 LEDs, left switch and potentiometer.

 

from microbit import *

# LEDs on pins 12, 13, 14, 15 & 16 (with 47-ohm resistors)

# Potentiometer on pin2

pins = [pin12, pin13, pin14, pin15, pin16]

# Colours R      Y      G      Y      R

def clear():

    for i in range(5):

        pins[i].write_digital(0)

def fill():

    for i in range(5):

        pins[i].write_digital(1)

#==== MAIN ====

print("\nSTART")

fill()  # Indicate program running

sleep(1000)

clear()

lsw_val = pin0.read_digital()   # Read left switch

while lsw_val == 0:

    pot = pin2.read_analog()    # Read potentiometer

    pointer = int(pot*5/1023)-1 # Integer: Range = -1 to 4

#    print(pointer)              # Help with de-bugging

    clear()

    if pointer != -1:

        pins[pointer].write_digital(1)

    sleep(100)

    lsw_val = pin0.read_digital()

clear()     # Tidy up - LEDs all off

print("\nFinished\n")

 

NB: An INTEGER is a whole number – no decimal part.

Predict what this program does and then run it. When you understand how it works add extra comments. Note the commented-out print statement which was used for de-bugging.

 

This task is quite difficult and will involve quite a bit of maths. Take out the potentiometer and replace it with and LDR and 10Kohm resistor as a potential divider connected to pin2. (See experiment 2 in the booklet.)

 

If you run the experiment again you will not get a full range of values (0 to 1023) from the A/D on pin2. Test with a suitable de-bugging print statement.

 

Change the program so that you can get a full-scale reading from all off, to the right-hand red LED lit, as the level of light falling on the LDR changes.

(Hints: You need to find the minimum and maximum readings from pin2 as the light changes. This will provide the input range which needs to be evenly divided into a range of -1 to 4.)

 

Ex 6 – Accelerometer and RGB LED

 

Take out the three LEDs on rows 24, 27 & 29 and replace them with the RGB LED. See experiment 10 circuit in the book. Re-run the previous program to check that they all light up.

 

from microbit import *

# RGB LED on pins 14, 15 & 16 with 47ohm resistors

# Switch with 10Kohm pull-down resistor on pin 0

running = True

while running:

    x_val = abs(accelerometer.get_x())  # Can exceed 1023

    if x_val > 1023:                    # Fix to max of 1023

        x_val = 1023  

    print(x_val)

    pin16.write_analog(x_val) # Green  Max allowed is 1023 

    sw_state = pin0.read_digital()

    if sw_state == 1:

        running = False

    sleep(200)   

pin16.write_analog(0)   # Tidy up

pin16.write_digital(0)

print("\nFinished\n")

 

This one is much easier. Predict what it does before you run it; then add extra comments.

 

  1. Use the y and z axes of the accelerometer to control the red and blue components in the RGB LED.
  2. Change the loop control to use Button B instead of the switch. Tidy up properly at the end.

 

An additional project to try on your own. Print the highest and lowest values produced by the LDR as the light changes.

 

Extras #1 – Using a 7-segment display

At the beginning of this review I suggested that I would have included a 7-Segment LED display as part of the kit. It offers a great deal of fun and educational opportunities at little cost if bought in bulk. Even one-off purchases are worth the cost. I suggest you buy at least 2 and you can expand the project to display values from 0.0 to 99. (TT could be used to display 100 – a ton?)

 

image

 

I looked in my ‘bits box’ and found an old, common cathode 7-segment display package with ten pins. It had F5101AH printed on one end. I looked on the Internet and found the specification on the Kitronik website https://www.kitronik.co.uk/blog/7-segment-display-datasheet/ .  The centre pins on the top and bottom are joined together and form the common cathode while the other pins are anodes to the 8 LEDS imbedded in the display. I quickly found which pin lit up each of the LEDs. I used two 47ohm resistors in series between a cathode pin and GND for extra safety. (ie 94ohms to limit the current and plenty bright enough.) I used pins 8, 6, 12, 13, 14, 15, 16 for A to G and 2 for the decimal point. Note: you have to turn off the display to use pin6 as an additional output pin.

 

I added a couple of switches with pull-down resistors on pins pin0 and pin1 to control the 7-segment LED.

 

from microbit import *

# 7-segment display with 2 switches (pull-down 10K)

#             on pin0 and pin1

  1. display.off() # Use display pins for GPIO

# Connections

#    A

#  F   B

#    G Segment positions

#  E   C

#    D  dp

#         A     B     C      D      E      F      G      DP

LEDs = [pin8, pin6, pin12, pin13, pin14, pin15, pin16, pin2]

# One row per digit - 0 to 9

#      A,B,C,D,E,F,G   Segments on the 7 Seg LED package

nums =[1,1,1,1,1,1,0,  # 0

       0,1,1,0,0,0,0,  # 1

       1,1,0,1,1,0,1,  # 2

       1,1,1,1,0,0,1,  # 3

       0,1,1,0,0,1,1,  # 4

       1,0,1,1,0,1,1,  # 5

       1,0,1,1,1,1,1,  # 6

       1,1,1,0,0,0,0,  # 7

       1,1,1,1,1,1,1,  # 8

       1,1,1,0,0,1,1,  # 9

       0,0,0,0,0,0,1,  # -

       0,0,0,0,0,0,0]  # Blank

 

def show_num(val, dp): #Displays one digit

    offset = val * 7

    for p in range(offset,offset + 7):

        x=p-offset

        if nums[p] == 1:

            LEDs[x].write_digital(1)

        else:

            LEDs[x].write_digital(0)

    # Decimal point needed?

    if dp == True:      # Light decimal point?

        LEDs[7].write_digital(1)

    else:

        LEDs[7].write_digital(0)

# +++ Main +++

show_num(11, 0) # Clear the display = blank and no dp

n = 0 # Initial value of display

print("\n  Left switch decrease value")

print("Right switch to increase value")

print("    Both switches to Halt")

show_num(11, 0)

while True:

    sd = pin0.read_digital()    # Down switch LEFT

    su = pin1.read_digital()    # Up switch RIGHT

    switches = sd *2 + su       # 0, 1, 2 or 3 is the range

    if switches == 2:           # Down switch only

        n = n-1

        if n < 0:

            n = 0

    if switches == 1:           # Up switch only

        n = n+1

        if n > 9:

            n = 9

    show_num(n, 0)

    print(n)

    if switches == 3:           # Both Up and Down! So HALT

        break

    sleep(200)

show_num(11, 0)                 # Clear the display

 

print("\nDone")

 

Predict what the program does before you run it.

Run the program and add extra comments when you understand how it works.

 

Extensions:

  1. Expand the codes at the top to include the extra letters a, b, c, d, e, f for hexadecimal numbers, base 16. (a = 10, b = 11, … f = 15)
  2. Change the switches section so that it can cope with values up to 15. (0 …f)
  3. Add a potentiometer and control the display (0 to f).
  4. Try an LDR to control the display. (Harder maths needed here.)

 

You may find that some of the pins light up the LEDs slightly as the program starts or when plugged into the breadboard. Do not worry. The Micro:bit has pull-up pins activated in its normal state and this is making the LEDS gently glow. Once you turn them off at the start of the program they will then react normally.

 

[If you use latest edition of Mu 1.0.0.beta.15 you can change the internal pull-up and pull-down on digital pins used for reading switches. Advanced users may find this useful.]

 

Extras #2 - Game – Using only the pixels on the display and Button B

 

# Zap the Rat - Python3 Game for BBC micro:bit

# Tony Goodhew - 5 June 2018

from microbit import*

def grid(n):  # Developed separately and dropped in

    display.clear()

    for y in range(5):

        for x in range(5):

            if n > 0:

                display.set_pixel(x, y,7)

                n = n - 1

 

#Circuit LED co-ordinates - round the edge

LEDx =(0,0,0,0,0,1,2,3,4,4,4,4,4,3,2,1)

LEDy =(0,1,2,3,4,4,4,4,4,3,2,1,0,0,0,0)

while True:

    display.scroll('Zap the Rat')

    sleep(10)       

    score = 0            # Rats zapped!

    opps = 0             # Zap opportunities

    p = 0                # Position of rat on circuit (0-15)

    delay = 150          # Initial delay between rat moves

    old_sw = 0                    # Last value of switch B

    running = True                # Loop control variable

    display.clear()

    display.set_pixel(3,2,9)           # Show Zap position

 

    while running:

        display.set_pixel(LEDx[p],LEDy[p],5) # Show rat

        if p == 10: opps = opps +1        # Incr opps - in (4,2)

        sleep(delay - score * 20) # Wait - gets faster

        sw = button_b.is_pressed()            # Read switch B

        pixel = display.get_pixel(4,2)         # Rat in Zap position?

        display.set_pixel(LEDx[p],LEDy[p],0) # Hide rat

        if old_sw == 0 and sw == True and pixel == 5: # Hit?

            score = score +1              # Increment hits

            display.set_pixel(1,score,9)  # Show hits

            if score == 3:                # Game over ?

                running = False           # Stop looping

            p = -1            # Position of next rat

        old_sw = sw            # Store switch value

        p = p + 1              # Update rat position

        if p > 15:             # Rat pointer out of range?

            p = 0              # reset to start position

           

    display.clear()  # Game over - display opportunities

    opps = opps - 3  # Remove successful opportunities

    display.scroll('SCORE')

    if opps > 25:  # Reduce missed opps to 25 max

        opps = 25

    if opps == 0:

        display.scroll("0") # Zero missed opps

    else:

        grid(opps)

    sleep(5000)  

    display.clear()  # Tidy display

 

This program does not use the kit components but illustrates the control of the pixels on the 25 LED display. This is also physical computing and similar techniques are used in bigger, brighter and more colourful add-on boards and Neopixels.

 

A ‘rat’ runs around the edge of the board and as it passes between the lit LED and button B the player must momentarily press button B -WHILE THE LED IS LIT. If you manage to ZAP the rat a score LED lights up on the left-hand side of the display and the next rat moves faster. Each missed ZAP counts against you.

You have to Zap 3 rats to finish the game. Your score is then displayed. Zero is perfect!

 

  + + + + +     + = rat track

  + S     +     S = Score

A + S   M Z B   Z = Zap position

  + S     +

  + + + + +     Rat moves anti-clockwise

  

Extensions:

Make the game harder:

  1. Make the ‘rat’ move faster at the start.
  2. Move the re-start position nearer the Zap position on each restart.
  3. Make speed of the ‘rat’ on the second and third runs move even faster.
  4. Make an impressive ‘0’ score display. Start with a single centre pixel, then a 3 x 3 square then a 5 x 5 square with the square moving out and in 4 times. (Develop as a procedure and then ’drop it’ into the script once it works.
  5. Stop the program when Button A is pressed at some point of your choice.

 

Editing this report on line is getting slower and slower so I think I had better call it a day with some final thoughts.

 

This is a very useful kit and can form a good introduction to Physical Computing with a BBC Micro:bit and learning to write code. My granddaughter and I had great fun using it. I recommend it.

 

I've enjoyed exploring the BBC Micro:bit so much that I have just bought a Kitronik :MOVE mini robot to continue playing.

 

I hope you have found my Python guide a useful addition. Comments and suggestions are welcome.

 

Thanks again to Randy and Element 14 for providing the hardware.

Anonymous