prom: primary robotics on micro:bits some first ideas · prom: primary robotics on micro:bits –...
TRANSCRIPT
PROM: Primary Robotics On Micro:bits – some first ideas
Adrian Oldknow [email protected] March 2018
The idea is for a 5 week block of lessons of about 90 minutes per week for Years 5 or 6 students to
learn the basic principles of coding the BBC micro:bit to respond to events, and to use them to
develop a project of their own devising. This mainly covers aspects of the Computing and Design
Technology curriculum, but also applies knowledge and understanding from the Mathematics and
Science curriculum at Key Stage 2.
The first 3 weeks are divided into 6 sections: (1) using the MakeCode editor, (2) using buttons,
gestures and LEDs, (3) using sensors, (4) making things happen, (5) using the pins, (6) working with
gadgets. In the last 2 weeks, groups of 2, 3 or 4 students develop their own projects to create an
autonomous device. In the first session they form their group, sketch out their preliminary ideas
and identify the resources they will need. In the next two sessions they build and refine their
project, and in the final session they write their group report.
A lot of the material can be covered with no hardware at all! The MakeCode on-screen simulation
of a micro:bit now extends to include many of the functions, such as using sensors, neopixels, pins
and making sounds. But having the real thing is a lot more fun, and is essential when it comes to
designing, making and testing autonomous systems, which is the aim of this exercise. Quite a bit of
the more technical stuff can be done with a few resistors, LEDs, crocodile clips etc. But as soon as
we come to use motors and servos we need more power than the 3V of the micro:bit provides.
The market changes very quickly, but for between £10 and £30 there is a wide range of accessories
and kits which make life much easier. We all know that school budgets are very squeezed. Many
secondary schools already have stocks of electronic components to support elements of the
Science and DT curriculum. Some also have stocks of BBC micro:bits which were not distributed to
students in 2016. There is plenty of scope for cooperation between primary and secondary schools
both in terms of resources and expertise. For about £30 you could put together a box of
components to support say a group of 3 pupils - £45 if you include a micro:bit. Ten of these could
support the kind of half-termly block described here. In one half term a school could run the block
with its chosen classes. If 6 schools clubbed together then they would only need to find c£75 each.
Parents, Rotary Clubs, IET branches, local companies etc. may all be willing to make contributions.
The Kitronik site is a good starting point for both information and for kit. There is a very useful
`Parents Complete Guide to the Micro:bit’. There is an overview of the micro:bit related products
here. Examples are the edge connector at £5, the Servolite board with neopixels at £11.40, the
Inventors Kit at £25, the Line-following buggy at £26.20 and the :MOVE mini buggy at £27.50.
Section 1: Using the Microsoft MakeCode editor
Use this link to open the Microsoft MakeCode home page:
https://makecode.com/.
Have a good look down this page and explore some of the other pages
on this site. From the Home page select the `Code’ button for micro:bit.
This takes you to the MakeCode block editor. There is a helpful guide in
the blog. At the top of the screen, in the blue area, there is the `Menu
bar’. At the left there is the `micro:bit simulator’. In the centre there is
the `toolbox’ with coloured writing and images. On the right there is the `editor’ where you build
up your code. At the bottom is a `Toolbar’. Pressing the `Getting Started’ tab runs a tutorial.
When you start a new program, two blue blocks appear in the
editor. We won’t need either of these in this first activity. In
order to delete something from the editor, just drag it into the
toolbox area, which changes to show a trash can. Release the
mouse button to delete the block. Repeat the process to delete
the second block. We are going to make the micro:bit respond to
different kinds of inputs. The simplest of these uses one or
other of the A or B buttons. Select `Input’ from the toolbox
to open up a menu of choices. Drag the `on button’ block
into the editor. Now select `Basic’ and drag the `show icon’
block into the editor. Put it in the jaws of `on button’.
Click on the little arrow at the side of the icon and choose a
pattern you fancy, like a
`diamond’.
Now you have created your first program.
Press button A on the simulator and check that it works.
Now create a second program in the editor to display a different pattern
when button B is pressed. There isn’t a separate `on button B’ block in the
`Input’ toolbox, but there is a little arrow next to `A’ in the `on button A’
block which allows you to create your own block for button B.
Some of the items in the toolbox have more than one menu of choices. The
`Basic’ tool has a `More’ option.
Create a third program in the
editor to clear the screen when
both buttons A and B are pressed.
Now you have created a program for the micro:bit which responds in
different ways depending on which combination of buttons is pressed.
Next we need to find out how to save our work and maybe share it with
others. Use the block in the middle of the toolbar to enter a title for your program.
If you want to keep a record of your work you can use the `Ctrl’ and `PrtSc’
keys to take a screenshot which you can paste into Word, and then `Crop’.
That’s the way I have created the images above. Click on the `Projects’ tab
in the Menu bar. You should now see that your program title now appears.
It is automatically filed for you somewhere `in the cloud’. If you want to
access your work from a different computer you will need to create a link
which you can use to retrieve it. Close the `Projects’ page and find the
symbol for sharing to the right of the `Projects’ tab.
This asks to you to confirm that you want
to publish your work. If you accept, then
it provides you with a link which you can
use to access your own file, or to send to
anyone you want to share it with.
When you open the link
in a browser you see a
different sort of display
which shows your blocks
and allows you simulate
the program, but if you
want to edit the program you need to press the red
`Edit’ button, which opens up the familiar MakeCode
editor display once more.
So far we have used MakeCode’s `Blocks’ editor which works in much the same way as the Scratch
programming language. But you can also switch into the `JavaScript’ programming mode which
shows the text version of the same program. This also has help features to tell you about the
available options.
Finally return to the `Blocks’ mode and explore the
options available from the `on shake’ block in the
`Input’ menu. Explore what the options mean and use
some of them to create other programs.
Section 2: Using buttons, gestures and leds
In the last section we didn’t use a real micro:bit at all. So now’s the time to plug in a real one and
explore some of things it can do. There is useful introduction on the Micro:bit Education
Foundation site.
There is quite a bit of technical jargon around this picture. So far we have met the 2 buttons and
the 25 LED display on the front. You may have tried programming the micro:bit to respond to one
or more of the `gestures’ like `shake’. These are detected by a device called an `accelerometer’
which is one of the sensors on the back. In order to create a program in the form which a
micro:bit’s processor can understand we have to convert it into a code known as `hex’. That is
done using the `Download’ button in MakeCode’s toolbar. We want to save the hex file.
So we have created the hex file called `microbit-Buttons-and-icons.hex’ in the `Downloads’ folder
on the computer’s hard-drive. Now we just have attached the micro:bit to the one of the
computer’s USB ports using the cable supplied. The big end plugs into the computer, and the little
end into the micro:bits `Micro USB Connector’ on the back.
You need to wait a few seconds until the
computer recognises the micro:bit as an external
memory device, usually called `MICROBIT (D:)’.
From the `Downloads’ folder, right-click on the
hex file you want to send to the connected
micro:bit. Find `Send to’ on the menu and then
select `MICROBIT (D:)’. A window will pop up to
show you how the download to the micro:bit is
progressing, and the yellow LED on the back next
to the micro USB connector will flash.
When this stops flashing and shows a steady light
then the micro:bit is powered up and ready to go.
Now you can check out that the correct things
happened when either or both of the buttons is
pressed. When you disconnect the micro:bit from the
USB cable the LED will go out and the micro:bit has no power. Attach a battery box with two AAA
batteries to the battery connector on the back. Now you should find that the program runs all on
its own. The technical term for an electronic device which can run its own stored program is called
an `autonomous’ device. Another term for this is a robot! (This was the Czech name for a forced
labourer!) Let’s now create a useful device – an electronic dice. (Actually `dice’ is a plural word, a
single one should be called a `die’.)
We need to be able to pick a random number between 1 and 6 and display it. We also need to be
able to generate such a random number whenever we perform a certain action like pressing a
button or shaking the device. We will need to use one of the purple `Math’ blocks in the toolbox.
Here is a sample
program to get the
feel of what we can
do with some of the
other blocks from the
`Basic’ tools.
`Forever’ just keeps
on repeating the two
commands for ever.
`Show number’ does just that. `pause (ms)’ waits the given number of milliseconds before moving
to the next command. A pause of 5000 milliseconds means a wait of 5 seconds. But we actually
need a number between 1 and 6, not one between 0 and 5. So we’ll introduce the idea of a
`variable’ which is a very important tool in computing.
We will set a variable called `die’ to the result of adding
1 to the random number between 0 and 5.
So here is a first go at making an automatic die
roller that generates a number every 2 seconds so
long as the micro:bit is powered up. Can you
adapt it by replacing the `forever’ by an `on’ block
so that new numbers are generated when an
action is made? Don’t forget to give your program a name.
But a real die has spots, not numbers! Can you see how the following program works?
Add more `if’ statements to produce suitable patterns for scores of 5,
4, 3, 2 and 1. Then you can remove the `show number’ block!
Some games require you to roll a six in order to start. How many rolls
do you expect this take? We can carry out an experiment to find out.
First we’ll see a useful idea to help keep your
programs tidy. It’s called a `function’. You need to
use `Advanced’ from the toolbox to find the
`functions’ tools. You can then create a function
called `Roll a six’ or any name you like.
This function uses a `while’ loop to keep rolling a
die until a 6 comes up. The number of rolls is stored in the
variable called `rolls’. We can use a very simple program block
to call this function and then to use the variable it produces.
Each time you press the `A’ button you will carry out the
experiment. The results can vary widely, from just 1 (if you are
lucky) to quite a large number.
So let’s adapt this to find the average number of rolls of a set
of several experiments. The variable `number’ is used to set
the number of rolls in the experiment. The variable `total’ will
add up the values of `rolls’ after each experiment. The
program uses a counted `repeat’ loop. After each experiment
the number of `rolls’ is shown, and then the program waits for
2 seconds. Finally it shows the grand total of the number of
rolls over all 10 of our experiments.
In order to find the average number we need to divide the
value of `total’ by the value of `number’. This can be done
by pressing button `B’.
So here is a sample of the whole experiment. The
numbers of rolls were: 7, 8, 8, 1, 3, 9, 7, 11, 8, 1, which
total to 63. Pressing button `B’ shows the average as 6. Hang on! 63 divided by 10 is 6.3, so we
need to understand something about the way the micro:bit does arithmetic, at least when using
the `MakeCode’ editor. In order to work faster and to use less memory, the micro:bit just working
with whole number, called `integers’. So dividing 10 into 63 goes 6 times and leaves a remainder of
3. In the `Math’, `… More’ toolbox there is a `remainder’ block.
So below there is a sleeker version of our complete program. Now the `A’ block just runs quickly to
show the `total’, and the `B’ block shows the average and the remainder.
Now, how about making an automatic device to play `scissors, paper, stone’?
What other random ideas can you come up with?
Some games, like chess, are played against the clock. Can we turn the micro:bit into a stop-watch?
We can use button `A’ to set it running, and button `B’ to
stop it and show the elapsed time. We have already found
that the micro:bit works with whole numbers, which
explains why the Basic `pause’ block works in milliseconds,
so we don’t have to use any decimals. This program uses a
variable called `time’ which will count the number of
seconds elapsed. The loop is a `tested’ loop which checks
to see if the button `B’ is being held down. Notice the
difference between `on button’ at the start, and `button’ in
the third line. Both are in the `Input’ toolbox. `not’ is in
the `Logic’ toolbox. The four Basic blue blocks flash the
clock every 500 milliseconds, to each pass of the loop takes
1000 milliseconds, or 1 second. When the `B’ button is
held down, the flashing stops and the elapsed time in seconds is displayed.
Can you turn this into an egg-timer, which flashes of buzzes after say 3½ minutes (or however you
like your egg cooked).
How about making a reaction timer? The program randomly chooses to display an `A’ or `B’
character. You must press the appropriate button. The program displays the time between its
display and your response.
Section 3: Using sensors
A sensor is an electronic device which detects the state of something. It might be just a simple
physical change, like opening and closing the fridge door, or it could be finding out your
temperature, like a thermometer. The buttons A and B on the micro:bit detect whether you have
pushed them down. The micro:bit has other more complicated sensors which can measure things
like the temperature or the amount of light falling on its front. As we have seen, it also has a clock
which can be used to control when things happen.
Think about some of the devices you have in your home. I get woken up by my bedside alarm
clock, set to go off at 07.00. When I get up, I change the setting on the knob which controls the
central heating. I have a warm, but not boiling, shower thanks to the control of the immersion
heater in the water tank. I make a cup of tea by boiling the kettle which automatically switches off
when it senses that the water has started to boil. I make some toast using a toaster which has an
adjustable timer so that it pops up when the toast is brown but not burnt. Modern cars have a
wide range of sensors to make things happen automatically. Can you think of some?
The micro:bit’s sensors can be accessed through the `Input’ blocks. Let’s see how we can turn the
micro:bit into a thermometer. The tiny program below just shows the temperature sensed by the
micro:bit as a whole number of degrees Celsius each time the A button is pressed. The simulator
shows an adjustable thermometer. Try dragging the top of the red `liquid’ in the simulated
temperature sensor up and down. What is the highest value it can show? What is the lowest?
Connect your micro:bit to the computer and download the program to it. Disconnect the USB cable
and plug in the battery box. What value does it show at room temperature? Try putting it in the
fridge for a bit and then press button A as you take it out. You could use it to check the freezer but
you ought to wear gloves to keep your fingers from freezing when you take it out. DON’T put it in
boiling (or any other kind of) water!
The next experiment tests the temperature and makes something happen if it is bigger (or less)
than a given value. Maybe we can show a warning signal if the temperature rises above 25°C and
sound an alarm if it falls below 15°C. We first need to store the current temperature in a variable
such as `temp’. Then we pick one of three actions to perform according to the size of `temp’.
The code opposite uses button A to start it running.
The green `while true’ block is a loop that will run
continuously. Use the `Variables’ tools to create the
variable `temp’. Use the `Input’ tools to pick up the
temperature. Use the `Logic’ tools to bring in an `if’
block. Use the blue symbol before `if’ to create your
own 3 choice structure as shown in the little diagram:
`if …. else if ….. else ….’. Use it again to hide it.
Below is the complete program. If you run it on the simulator, the noise will come from your
computer’s speakers. If you want to make the micro:bit generate a sound when it is detached from
the computer you will need to connect a buzzer to the 0 and GND pins using crocodile clips or wire.
Press button `A’ to run the program, and drag the thermometer level up and down to check all
three states. You have now created your first `stand-alone’ system using a micro:bit. This is same
structure as the program which controls the central heating of a house. In that case when the
temperature falls below a certain level the heating is turned on and stays on until the temperature
is warm enough, when the heating is turned off again.
In order to be able to collect data about the
temperature when the micro:bit is not visible,
we can create a program which records the
lowest value reached in a certain period. When
button `A’ is pressed the temperature is read
every second for 10 seconds. The variable `min’
keeps track of the lowest temperature
recorded, and the variable `clock’ keeps the
time in seconds.
When the program has finished, the letter `E’ for
`End’ is displayed. Then you can press button `B’
to read out the lowest temperature recorded. We
only used collected data for 10 seconds to check
that the simulator was working as expected. Now
you can change value in the `while’ statement do
300 say, which will collect data for 5 minutes. Now you can download it to the micro:bit,
disconnect the USB cable and connect the battery box. Then you put the device in the fridge, close
the door and leave it to run. When you take it, after at least 5 minutes have passed, you should see
the letter `E’ on the display. Then whatever the temperature is around you, pressing button B will
show the lowest temperature it reached during its
stay in the fridge.
You have now seen and used one way to make the
program loop until a certain condition is met – in this
case until the clock reaches a given value. We could
equally as well have used a different structure called
a `counted loop’. The `Blocks’ tools include a
`repeat …. times’ block as shown alongside. So now
we can capture data from scientific experiments.
Now it’s your turn to think of things you can do with the light
sensor. You can read its value from the `light level’ variable in
the `Input’ tools. It produces a number between 0 and 255
measured on the front of the micro:bit. Could you create a
rear lamp for your bike which displays different patterns of
LEDs according to the amount of light received?
Can you create a compass so that your micro:bit tells you in
which direction you are walking?
Can you create a brake lamp which detects when you are slowing down?
You can also explore using external sensors connected to the pins of the micro:bit.
Here are some familiar objects
which use sensors. Can you
take photos of some more?
4. Making things happen
By now we have met and used most of the features and programming blocks we need to create
useful systems. In this section we will explore some of the cheap external gadgets we can use to
make electronic circuits which the micro:bit can control. We do need to understand a bit about
electronic components, as well as the ways in which the micro:bit can be connected to them. As
you know, the micro:bit is set to work from two AAA batteries, which provide 3 volts. While this is
fine for some electronic components, it is not enough to power the motors we can use for
mechanical output. So in this section we will explore some of the relatively cheap components and
systems which we can use with micro:bits. We will first look at some ideas for displays using LEDs.
There is an `Led’ toolkit which we have not previously explored. The program below shows 2 of the
25 LED `pixels’ lit using `plot x’ blocks. The x-coordinates range from 0 to 4 going across the display.
The y-coordinates range from 0 to 4 going down the display. They also allow you to control the
brightness of each LED individually. As a first project let’s try and simulate a set of traffic lights.
Traffic lights have 3 lamps. The top one is red, the middle one is amber
and the bottom one is green. They change in the sequence:
red, red & amber, green, amber and back to red. For the simulated
lights in the MakeCode editor we will just use the top three LEDs in the
first column and not worry about their colour.
Here is my first attempt.
Can you find where I’ve
gone wrong, and fix it?
Adjust the waiting times
between lights so that the
red and green ones are
displayed for longer
intervals than the
red/amber and amber
ones.
We can carry on using the
simulator for a bit longer
as there is a special class of coloured LEDs which it supports. These are known as `neopixels’. They
come in quite a variety of forms:
In order to control these devices there is an additional package you can use to add `neopixels’ to
the toolkit. In the MakeCode editor make sure that the `Advanced’ tools have been activated.
Scroll down the tools until you see: `Add Package’. Select this. Now you can add `neopixel’.
The basic idea is that you have a
chain of individual NeoPixels
attached to one of the micro:bits
pins P0 to P20. You use the
`Variables’ tools to give your set of
neopixels a name, such as `pixels’.
In the `on start’ block you tell the
editor the number of LEDs in your
chain and the pin to which they are
attached. Then the simulator
provides a strip for you!
The `on button’ block sets up the first part of the sequence: showing the red light. Note that you
have to use a `show’ block to make the `set pixel’ block be performed.
As with the earlier program I have not
completed the full sequence of instructions.
Can you fix it, and adjust the timings?
Of course you can have a lot of fun just flashing
different patterns of coloured lights. Better still
if you can add some music!
You may have seen that there is a `Music’ tool in
the toolbox. This provides sound using your
computer’s loudspeakers when you run the
simulator. If you want to make sounds on the
micro:bit itself you will need to attach either
speakers or headphones.
When you run the `Music’ commands on an actual BBC micro:bit, they output to pin P0. In the next
section we will how to make more use of the large number of the micro:bit’s input and output pins.
By now you should have written and saved several programs for the micro:bit. Sometimes when
you press the `Projects’ tab you may not find the program you are looking for, usually because you
forgot to save it. But all is not lost.
If you transferred your program to a
micro:bit you will have saved it as a hex
file to the `Downloads’ folder on your
hard drive. Up to now we have used
the hex files to send code to an
attached micro:bit. But MakeCode can
also convert hex files back to blocks in
the editor. Just select `Import File’,
browse in the `Downloads’ folder and
select the hex file you want to import.
5. Using the micro:bit’s input and output pins.
A very helpful source of ideas and components for connection to the BBC micro:bit is the Kitronik
website. Their `Inventor’s Kit for BBC micro:bit’ describes some simple experiments which are easy
to make. We will start with their free tutorial on using an analog Light Dependent Resistor (LDR) as
an input. This uses just two cheap small electronic devices: an LDR and a 10 kΩ resistor. So already
we have some jargon to decode! Devices like switches and buttons have just a few possible
different states – maybe just on or off. These can be represented by numbers like 0 and 1. They
are called `digital inputs’. Devices like knobs and temperature sensors can change continuously,
varying the voltage sent to the micro:bit. These are `analog inputs’. The photograph shows a
micro:bit slotted into something
called an `edge connector’, so
that each of the segments of the
gold-coloured bar at the bottom
of the face of the micro:bit is led
out onto a different pin. The
diagram below the micro: bit
shows how the LDR and resistor
R1 are to be wired up to these
pins.
The components are pushed
into the holes of what is
known as a `bread-board’.
Yellow, red and black lead
connect the appropriate
column of holes on the board
to the micro:bit’s pins P0, 3V
and GND. A resistor is used
to ensure that only a small
current passes through the
LDR so that it doesn’t burn out.
Resistance is measured in a unit
called the `Ohm’, written as the
Greek letter `omega’ Ω. We are
using a large resistance of 10,000
Ohms. Resistors have patterns of coloured bands round them which identify their resistance. You
don’t need a `prototyping’ kit. You can just use crocodile clips to attach the components to the
micro:bit as in the photo above. So that’s the hardware sorted. We just need to write some code
to see how the LDR can be used. This uses the `Advanced’ section of the toolbox which has a set of
tools called `Pins’.
First use `Variables’ to create a variable called `light’. Then use `Input’ to create an `on button’
structure. Use `Pins’ to select `analog read’. The value returned will be between 0 and 1023. So if
we divide the value by 1000 we will normally get a value between 0 and 9. Running the program on
the simulator, you can click in the `Pin0’ area and adjust the level up and down. Then press button
`A’ to see the corresponding value. When you download this to a micro:bit you change the light
intensity falling on the face of the LDR by shining a torch or covering with your hand.
So now we can add an output in the form of a `light emitting
diode’ LED. We want the LED to shine brighter when it is
darker, and vice versa. So we just need to create another
simple circuit using an LED and a 47Ω resistor attached to
pin P1. We can read the light intensity using the LDR on Pin
P0, then subtract the result from 1023 and output this value
to pin P1 to control the brightness of the LCD.
The LDR and 10kΩ resistor are on left of the board. One leg
of the resistor is in the top row of holes, shown in blue, which is connected by the black wire to the
GND pin. One leg of the LDR is in the second row of holes, shown in red, which is connected by the
red wire to the 3V pin. The other legs are in the same column of holes as the yellow wire which is
connected to the P0 pin. So that’s the analog input side of the business.
We have to take a little more care with the LED since its
shorter leg needs to be connected to GND, using the blue
wire. Its longer leg is connected through the 47Ω resistor to
pin P1 with the green wire. The circuit is shown in the photo
above, and the code is really very simple.
Of course if we wanted to make this into a smart lamp we would do away with the `on button’ and
use a `forever’ block instead.
Now we have got a green LED in action, we could make our
traffic lights on the bread-board using a red and a yellow LED
and two more 47Ω resistors. Here is a rough version of the
program. As before, the sequence isn’t quite right, and the
pauses need to be changed. For testing purposes I have just
used a counted loop for four sequences when button A is
pressed. On the simulator, the pins P0, P1 and P2 show a
sequence of 0s and 1s as the lights are switched on and off.
The circuit is pretty straightforward. The GND pin is
connected to the negative, blue track on the bread-board.
The shorter leg of each LED is connected to the blue track. The longer leg is connected through a
47Ω resistor to pins P0 (green), P1 (yellow) or P2 (red) of the break-out board. Can you fix the
program to perform the correct sequence?
We will finish this section with a quick glimpse at controlling a motor. For
most applications, such as buggies, the 3V power supply is not sufficient. But
we can illustrate the theory with low power versions, such as the £5 Motor &
Fan from Microbit Accessories, shown connected to a micro:bit with the
supplied crocodile clips.
To test this I have connected the
motor to the GND, 3V and P0
connections on the micro:bit. Button
A turns the motor on, button B turns
it off.
See if you can now make a model of a simple heating system which senses the temperature. If it is
too hot it turns the fan on until the temperature is cool enough. If it is too cold it turns on one or
more LEDs to simulate a heater, which is turned off when the temperature is warm enough.
The same dealer stocks a water pump and water sensor. You can make an automatic plant
watering system which turns on when the soil is too dry! Read more here.
6. Working with gadgets
Many of the standard construction kits like K’nex, Lego and Meccano have electric motors and
other bits of electronics which can be built into projects. Try using Google to see if you can find
some examples of how others are using micro:bits to work with them. I found this video and this
blog. Returning to the Kitronik Inventor’s Kit, there is a full description of Experiment 4, to use a
transistor to drive a fan motor. The components required are a
motor with fan blade, a 2.2kΩ resistor and something called a
NPN BC337 transistor. You can find out more about transistors on
BBC Bitesize. The photo shows the simple layout on the
Inventor’s Kit bread-board, but you can also make the circuit with
crocodile clips.
The example program just sets
a variable called `Duty’ to a
number between 0 and 1023
to write to pin P0 to control
the speed of the motor. When
you press button A, `Duty’ is
set to zero, and the motor is at
rest. The first `while’ loop
steadily increases `Duty’ by 1
until it reaches the maximum
of 1023. The function `Change
speed’ writes `Duty’ to pin P0,
increases `Duty’ by the value
of the variable `item’ which is initially set to 1 and hangs about a short while (one hundredth of a
second). When the maximum speed is reached, the value of `item’ is set to -1 so that the second
`while’ loop steadily reduces `Duty’ by 1 until it reaches 0, when the motor stops and the program
finishes.
There is another very useful electronic device to set the resistance by
turning a knob. This is called a `potentiometer’. So let’s put a
potentiometer into the circuit, and read from it to control the speed of
the motor. The potentiometer (or `pot’ for short) is on the right hand
side of the board. The right leg is connected to GND, the left leg to 3V
and the middle one to pin P1.
All the program does is to read the value from P1 and write it to P0. In the simulator you can drag
the coloured shape on P1 up and down. If it is a value greater than 100, the process will continue,
but if you turn the pot so that the value is less than (or equal) to 100 that is interpreted as the
signal to stop, so a 0 is sent to P0 to switch the motor off.
You may well have some lights at home on `dimmer switches’. These are just potentiometers
controlling the current reaching the light bulbs. Can you build a dimmer circuit for a micro:bit using
a potentiometer, an LED and a 47Ω resistor?
The final part of this section is about controlling motors to move something. This might be to turn
one or more wheels on a buggy, or to make small movement to control the position of something
like a level-crossing barrier. In each case we need to give the motor more power than is available
on the micro:bit.
A useful way to do this is with a pre-made board which provides 4.5V
or 6V to the motor from 3 or 4 AAA or AA batteries, and also has a
voltage converter to send 3V to power the micro:bit. We’ll illustrate
this with the Kitronik Servolite board with neopixels at £11.40.
This has an on/off switch at the top and a row of 5 neopixels beneath.
Above and to the left of the `Kitronik’ label is a row of three pins
labelled SERVO_1, with another set of the right-hand side of board
labelled SERVO_2. An introductory guide is here. Let’s start with
flashing some of the neopixels. You need to use `Advanced’ to be able
to `Add package’ and then import the additional `Neopixel’ block. The
pixels are numbered 0, 1, 2, 3, 4 from left to right. These are
controlled through pin P0.
We’ll start with an `on
button’ block which uses
`Variables’ to create a `set
item’ block. Use the little
red arrow down to
`Rename’ the variable `index’ to
something meaningful, like `pixels’.
From `Variables’ use `set’ to define the
number of neopixels and the pin
number to use. From `Advanced’ use
`Functions’ to create a new function
named `Flash’. This will turn on each
of the first 3 neopixels in turn before
clearing them all. You have to
remember to use a `pixels show’
command after any changes to see the
effect. Our little program uses a
counted loop to display the pattern
just four times. This should work fine
in the simulator. Once you have
downloaded the program to the
micro:bit you can disconnect the USB
cable from the micro:bit and switch
the power button to `on’ on the Servolite board. Then, when you press
button `A’, the lights should shine brightly.
The word `servo’ is used for a particular kind of electric motor. Kitronik sell
two varieties of servo motors. The one on the left is a Mini 180 Degree Rotation Servo with
accessories costing £3.06. The picture in the middle show the accessories which allow the servo to
rotate an arm with holes drilled in it to move an attached object using some stiff wire or something
similar. The one on the right is a 360 Degree Continuous Rotation Servo costing £4.62.
Here is an example of a single servo used in a project for a milk-can robot.
Here is a simple test program for a 180° servo. The `servo write’ block is in the `Advanced’ `Pins’
toolbox. As soon as a `servo’ block is used, the simulator adds a servo to the correct pin. The blue
wire is attached to GND, the red one to 3V and the mauve one to P0.
The `on start’ block moves the servo’s arm to its central position. Pressing button A moves it to the
extreme right, button B moves it the extreme left and pressing A and B together choses a random
position.
These photos show a
180° servo controlled via
pin P0 driving a Lego
semaphore signal with a
large paper clip bent to
form the connection rod
to rotate the signal.
The 3 volt power supply
on the micro:bit is OK for
use with a single servo
for light duty work. To make a walking robot
like the one shown here you may have as
many as eight independent servos. The
Kitronik I2C Servo Driver board shown here
costs £15 and can drive up to 16 servos using
an external 4.5V battery pack.
Kitronik has developed its :MOVE MINI robot
buggy kit for the micro:bit (not included) at
£27.54. This assembles into a crawling vehicle
powered by two 360° continuous servo motors
driven from 3 AAA batteries on the underside
of the Servolite board (included). You can read
the instruction booklet here.
The motor is sent a number between 0 and 180. This number
controls the speed of the motor. 90 is at rest, 180 is fast
forward and 0 is fast reverse. The servo attached to pin P1
drives the left wheel and the one attached to P2 drives the
right wheel. So in order to move in a straight line forward,
one will be sent 0 and the other 180.
The test code should move
forward when A is pressed,
move back when B is pressed
and stop when A and B are
pressed. The simulator doesn’t
understand that we will be
using 360° continuous servos,
so it just indicates how 180°
servos would interpret the
code. The next step on the real
vehicle is to measure how far it
moves in a given time – say 1
second.
Can you devise a program which makes the vehicle move forward for 1000 milliseconds and then
stop? It isn’t very complicated.
How do you think we can make the vehicle turn left, say? We need the motors to be turning the 2
wheels in different direction, so we need to set both motors to 0 to turn in one direction, and to
180 to turn in the other direction. Can you work out a way to make it turn through 90° left or right?
Kitronik also provides additional packages for the MakeCode editor to help make programming
servos easier.
Press the `wheel’ icon at the right-hand end of the upper toolbar.
Select `Add Package’ and type `Kitronik’ in the search bar. You will
see three choices appear. The left hand one is for the Servo Lite
driver board. This adds a `Kitronik’ menu in the toolkit.
Now you can use `Scratch’ like commands to move forward or back a given distance, and to turn
left and right by a given angle.
As well as programming the buggy’s movement directly with the on-board micro:bit, you can also
control it remotely. This note takes you through coding the micro:bit to be controlled remotely
with the Bitty Game Controller for Android or iOS. This note explains how to use a second micro:bit
to control the :MOVE mini with its built in `Radio’ and `Control’
commands.
An alternative to using 360° continuous servo motors is provided
in the Kitronik Line Following Buggy kit at £26.20 (excluding the
micro:bit). This includes a Motor Driver Board and a pair of Right
Angle Geared Hobby Motors.
The `Kitronik’ package adds another
couple of blocks to make using the
motors easier.
So that concludes this introduction to using the MakeCode editor to write programs which make
things happen – either with the on-screen simulator, or, better still, with the real kit!
What happens next?
The idea is for you to work as part of a small team (2, 3 or 4 of you) to design your own robotics
project for a micro:bit. It can be as simple or as sophisticated as you like, but it must make the
micro:bit do something interesting. You will have about 3 hours of lesson time over 2 weeks to
work on this, but of course you can do more in your time if you like. You should keep a log of what
you are doing, including screen shots of the block programs you create and test, as well as
photographs of your system. You should also create two A4 sheets which can be pinned up on a
display board to explain to others what your system does.
Happy engineering!