12
Data-logging with BBC micro:bits and MakeCode for modelling with Excel and GeoGebra Adrian Oldknow University of Chichester April 2018 [email protected] The BBC micro:bit is a remarkably cheap, friendly and versatile tool with a capacity to revolutionise learning across the STEM subjects. This article show how it can be used with simple and cheap sensors to capture data from famous experiments such Newton’s law of cooling, and the discharge of a capacitor. The micro:bit can be easily programmed in a variety of languages. By far the most easy to learn and versatile of these is with JavaScript using the free block editor called MakeCode developed by Microsoft. Originally this was only available through a web browser, but now there is a free Windows 10 App for it which includes some very useful features for data-logging. Data collected with a micro:bit can be transferred to via a serial cable connected to a USB port and stored as a comma separated variable CSV file. This can be opened in Windows Excel for display and analysis. The data can also be copied and pasted into other applications such as the free, open- source modelling package called GeoGebra. So let’s get cracking with setting up the experiment. The micro:bit has a number of built-in sensors including light, temperature, acceleration and magnetic field. It also has over 20 input and output pins which can be used to exchange digital and analog data with external devices. I am going to use a dish of hot water to warm up an external temperature probe connected to the micro:bit with cables and crocodile clips. There are 5 holes on the micro:bit designed to accept crocodile clips. From left to right they are called P0, P1, P2, 3V and GND. The sensor I am going to use costs £3.90 from microbit-accessories. The red cable connects to 3V, the black to GND and the green to any of P0, P1 or P2. I will use P0. To illustrate output I will also connect an external red LED to show when data-collection is taking place. This costs £1.90 from the same source. The black cable also connects to GND and I will connect the green cable to pin P1. The photo shows the very basic layout of the experiment. The white dish contains hot water from the kettle. The temperature probe is held just above the surface of the water for a short while to warm it up. Then it is removed from the dish and left to cool on the table while data is being collected. We need to write a program for the micro:bit to turn capturing on and off and to do something with the data read in at P0. First we need to find out some technical details about the temperature probe, which are here. The relevant section is copied below. The warmer the probe the greater the voltage it outputs. At 25°C it outputs 0.75 volts. Each change of 1°C in temperature changes the output by 0.01 volt. Voltage inputs on analog pins like P0 from0 to 3.3 volts are converted to integers between 0 and 1024.

Data-logging with BBC micro:bits and MakeCode for modelling … · Data-logging with BBC micro:bits and MakeCode for modelling with Excel and GeoGebra Adrian Oldknow University of

  • Upload
    others

  • View
    8

  • Download
    0

Embed Size (px)

Citation preview

  • Data-logging with BBC micro:bits and MakeCode for modelling with Excel and GeoGebra

    Adrian Oldknow University of Chichester April 2018 [email protected]

    The BBC micro:bit is a remarkably cheap, friendly and versatile tool with a capacity to revolutionise

    learning across the STEM subjects. This article show how it can be used with simple and cheap

    sensors to capture data from famous experiments such Newton’s law of cooling, and the discharge

    of a capacitor. The micro:bit can be easily programmed in a variety of languages. By far the most

    easy to learn and versatile of these is with JavaScript using the free block editor called MakeCode

    developed by Microsoft. Originally this was only available through a web browser, but now there is

    a free Windows 10 App for it which includes some very useful features for data-logging. Data

    collected with a micro:bit can be transferred to via a serial cable connected to a USB port and

    stored as a comma separated variable CSV file. This can be opened in Windows Excel for display

    and analysis. The data can also be copied and pasted into other applications such as the free, open-

    source modelling package called GeoGebra. So let’s get cracking with setting up the experiment.

    The micro:bit has a number of built-in sensors including light, temperature, acceleration and

    magnetic field. It also has over 20 input and output pins which can be used to exchange digital and

    analog data with external devices. I am going to use a dish of hot water to warm up an external

    temperature probe connected to the micro:bit with cables and crocodile clips. There are 5 holes on

    the micro:bit designed to accept crocodile clips. From left to right they are called P0, P1, P2, 3V and

    GND. The sensor I am going to use costs £3.90 from microbit-accessories.

    The red cable connects to 3V, the black to GND and the

    green to any of P0, P1 or P2. I will use P0. To illustrate

    output I will also connect an external red LED to show

    when data-collection is taking place. This costs £1.90

    from the same source. The black cable also connects to GND and I will connect

    the green cable to pin P1. The photo shows the very

    basic layout of the experiment. The white dish contains

    hot water from the kettle. The temperature probe is held

    just above the surface of the water for a short while to

    warm it up. Then it is removed from the dish and left to

    cool on the table while data is being collected. We need

    to write a program for the micro:bit to turn capturing on

    and off and to do something with the data read in at P0.

    First we need to find out some technical details about the

    temperature probe, which are here. The relevant section is copied below. The warmer the probe

    the greater the voltage it outputs. At 25°C it outputs 0.75 volts. Each change of 1°C in temperature

    changes the output by 0.01 volt. Voltage inputs on analog pins like P0 from0 to 3.3 volts are

    converted to integers between 0 and 1024.

    mailto:[email protected]://microbit-accessories.co.uk/shop/page/2/http://microbit-accessories.co.uk/shop/sensor/temperature-sensor/

  • So now we just need to install the MakeCode App. This is described here, and can be found in the

    Microsoft store here. One advantage of the App is that you do not need to be connected to the

    internet. But there are also some powerful features now available in the App which are not (yet)

    available in the browser version here.

    Here is the basic layout of

    the block editor. The large

    are on the right is where we

    will develop the program

    graphically. The picture on

    the left is a simulated

    micro:bit where you can test

    your code. The middle area

    has a list of the types of

    blocks available to use. The

    area at the bottom allows

    you to name and save your program as a hex file which can be downloaded to a micro:bit attached

    to the USB port. The micro:bit device is a microcontroller designed to respond to events, so the

    programming style is just a little different from other languages I have used like Basic, Fortran or

    Python. It is much closer to Scratch, where several things can appear to be happening at once.

    https://support.microbit.org/support/solutions/articles/19000075127-makecode-for-micro-bit-windows-10-apphttps://www.microsoft.com/en-gb/store/p/makecode-for-micro-bit/9pjc7sv48lcx?rtc=1https://makecode.com/

  • So here is my test program for the experiment. There is not one program with a beginning, middle

    and end, but three separate blocks each triggered by a different event. The first one, headed `on

    start’ is what to do when the micro:bit first starts running. The `on start’ block comes from the

    `Basic’ menu which shows up as blue blocks. Using the `Variables’ menu I have created a variable

    called OK. From the same menu I have picked up a `set’ block. I don’t want OK to have a numerical

    value, just a logical one if either `true’ or `false’. These are found in the `Logic’ menu. In order to

    get some feedback about what’s going on, I have used the `Basic’ `show string’ block to write a

    letter `R’ on the 5x5 LED display to show we are Ready to capture data.

    The block that does all the work is the `on button A’ block from the `Input’ menu. To access the I/O

    pins we need the `Pins’ block, which is in the `Advanced’ section towards the bottom of the list.

    The `digital write’ block just sends a 0 or 1 to the selected pin. In this case we send a 1 to pin P1 to

    turn the external LED on to show we are collecting data. The green `while’ block comes from the

    `Loops’ menu. In this case we will keep going round this loop until the variable `OK’ is changed

    from `true’ to `false’. So now have a look at the `on button B’ block of code. We press button A to

    start the data-logging, and when finished we press button B to end it. So that little block is pretty

    much the reverse of the `on start’ block, with the addition of a `digital write’ block to switch the LED

    off. So now we can get back to the contents of the `while’ block. This first uses `set’ from the

    `Variables’ menu and `analog read’ from the `Pins’ menu to store a number between 0 and 1023 in

    the `Temp’ variable representing the voltage on pin P0 connected to the temperature probe. The

    `map’ block from the `Pins’ menu gives us a neat way to rescale the `Temp’ variable to another

    variable `code’ so that a value of 200 produces a 0 and a value of 311 produces a 9. These values

    more or less correspond to a range of temperatures between 20°C and 50°C. We want to send the

    `Temp’ variable back to the Windows 10 PC down the serial cable, so from the `Serial’ menu we use

    `serial write’ to send the string `t’ and the value `Temp’ back to the computer. We can also use

    `show number’ to display the `code’ value between 0 and 9 on the LEDs. Finally we use the `Basic’

    `pause’ command to wait 200 milliseconds before taking the next reading.

  • Now we have written the code in the editor we can test it on the simulator. When you click on the `on start’

    block the program starts and an `R’ is displayed. When you press the A button, pin P1 turns red and shows a

    1. The LEDs show a number between 0 and 9. If you click on P0 you can drag the top level of the red

    shading to change the value manually to around 300. If you click on the `Show data Simulator’ button the

    display changes from the code to a real-time graph which clearly shows changes as you drag the P0 level

    carefully up and down. There is a Pause/Record button at the top right. This is one of the features which is

    in the App but not the browser version of MakeCode. Press button B to stop the logging and click the small

    arrow over the top right of the graph to return to the code. Make sure you save it with a sensible name.

    To rerun the simulation, use the `refresh’ icon second from the left below the simulated micro:bit.

    Now we are set up to go live. Click the `Download’ button below the simulator and this will

    automatically squirt the hex version of your program down the USB cable onto the connected

    micro:bit. This is another new feature in the App. You should see an `R’ appear when the program

    has loaded. Warm the temperature probe up by holding it close to the hot water. When ready, put

    it on the table, press the A button on the simulator and then press the A button on the micro:bit.

    The external LED shpuld now turn red. A second `Show data’ button will appear on the PC, this

    time for the `Device’. As shown below, you should see the numbers on the LED count down as the

    probe cools. You should also see a dynamic graph of the output from the probe.

    When you have collected enough data, press the green `pause’ button on the screen and the B

    button on the micro:bit. Finally press the blue `download’ button at the top right of the screen.

  • This will automatically save a CSV file of

    your logged data on your PC and then

    open it up in Excel. Highlighting columns A

    and B you can insert a scatter graph of the

    raw temperature data against time and

    see rate at which temperatures are

    decaying depends on the difference

    between the temperatures of the probe

    and the environment in the room. The bigger the difference, the faster it cools. To do some more

    sophisticated analysis we can copy the data from columns A and B to paste into a different

    application.

    The one I usually use for modelling data is the free open-source GeoGebra software. This is

    available in a variety of forms for a variety of platforms. I am using GeoGebra Classic version 5 for

    Windows which I have installed on my Windows 10 laptop. It is available here. This has a number

    of `Views’. I am using three of them. The `Algebra’ view on the left shows numbers, formulas etc.

    The `Spreadsheet’ view is in the middle. The `Graphics’ view is on the right. I also have an `Input’

    bar at the bottom. With the cursor in the cell A1 of the spreadsheet you can right-click and select

    `paste’ to copy in the data we exported from Excel to the clipboard. We can create a new column

    C to change voltages into °C using the formula `= 25 + (B1 - 233)/3’ in

    cell C1 and copying it down. In order to create a scatter plot we use the

    `Two Variable Regression Analysis’ tool. First click on the C label and

    then with CTRL held down, click on the A label. Now select the tool.

    https://download.geogebra.org/package/win

  • You will now create a scatter plot in the Graphics view. You can use the mouse and its wheel to

    resize the axes. With a right-click you can also select to change the ratio of the scales on the x- and

    y-axes. You can right-click on any object to change its properties. If you right-click on the List L1 in

    the Algebra view you can change the colour, style and size of the data points. Using the second

    icon in the Graphics view you can create a new point A on the y-axis which can be dragged up and

    down. You can also use the fourth icon to construct a line through A perpendicular to the y-axis. I

    have changed the colour of the line `l’ to green. Create B as the intersection of the axes, i.e. the

    origin (0,0). Use the third icon to create the segment AB, and colour it red. Use the eighth icon to

    measure the length of AB. I have renamed it to `g’. This value, shown as 27.14 represents the

    current room temperature, which you can change by dragging B up or down on the y-axis. Now we

    can construct a fourth column D in the spreadsheet using the formula `= C1 – g’ in cell D1 and

    dragging it down. Column D now represents the temperature difference between the probe and its

    environment.

    In order to fit a model to the graph we need to have an idea about what sort of mathematical

    function is the most appropriate. Choices might be linear, quadratic, cubic, polynomial, power,

    sine, log or exponential. Newton used differential calculus to show that the model for this kind of

    decay is `negative exponential’, with an equation of the form f(x) = A + B.ekx. A is the limiting

    temperature to which the data are approaching i.e. room temperature. B is the excess

    temperature when data-logging starts, and k is a negative constant. Create the point D on the y-

    axis corresponding to the first piece of data. The best I could manage was (0, 21.55). Create the

    segment AC and measure its length `h’. This is the value I’ll use for B. In order to experiment with

    the decay constant k, we can create a `slider’ using the tenth icon. You can change the lower,

    upper and step values for this variable. After some experiment I chose -0.1 as the minimum, 0 as

    the maximum and 0.002 as the step.

    Using the Input Bar we can enter a formula like f(x) = h*e^(k*x) - g. We have already defined the

    variables g, h and k in the Graphics view. In order to enter the symbol e, use the little α button at

    the right end of the Input Bar. This brings up a table of special symbols which includes e. The graph

    of the formula is now displayed and you can change its colour. Dragging the k slider you can now

    adjust the shape of the

    mauve curve to fit the

    data points as closely

    as possible. Now we

    have a model curve

    which approximates

    the data we can

    explore its slopes as

    the rates of cooling.

    Construct point E on

    the x-axis and the

    perpendicular to the x-

  • axis through it. Create the point F where it intersects the horizontal through A, and the point G

    where it intersects the model curve y = f(x). Create the segment FG and measure its length t. So as

    we drag E along the x-axis, the value of t represents the excess temperature of the probe over the

    environment. Use the fourth icon to create the tangent to the model curve at G, and measure its

    slope s. In the Input Bar enter the formula `ratio = s/t’. As you drag E on the axis, the values of

    both t and s change, but their ratio stays constant, equal to k.

    So the hardware needed for this experiment was a BBC micro:bit (£15) with a temperature probe (£

    3.90). The software was free!

    So let’s set up a second experiment for you to try for

    yourself. This is an experiment for a similar model of

    exponential decay, this time of the charge in a capacitor.

    I have set up the experiment on the edge connector and

    bread-board prototyping kit marketed by Kitronik as the

    Inventor’s Kit costing £25. The circuit is adapted from

    Experiment 9. But the actual components can be bought

    much more cheaply, with the legs twisted together and

    three leads with crocodile clips to GND, 3V and P0. You

    just need a 470 μF capacitor, a pair of 2.2 kΩ resistors

    and a pair of switches or buttons. The idea is hold down

    the left hand switch to charge up the capacitor fully to

    3V. Then to hold down the right-hand switch until the

    capacitor is discharged. The voltages are logged via pin

    P0.

    The program sends the initial voltage

    reading from P0 to the MakeCode App via

    the serial cable, which causes the `Show

    Data Device’ message to appear below the

    simulator. Now you can hold down the

    left switch to charge up the capacitor.

    When you are ready, press the A button to

    start. You now have 5 seconds to release

    the left switch and start the `Show Data

    Device’ running before you press and hold

    down the right button to let the

    capacitor discharge fully. Then press

    the green `Pause’ button above the

    graph in MakeCode. Remember to

    download this to a CSV file

    straightaway with the blue button!

    https://www.kitronik.co.uk/5603-inventors-kit-for-the-bbc-microbit.htmlhttps://www.kitronik.co.uk/blog/inventors-kit-experiment-9-help

  • As you can see you can get an impressively smooth graph provided the data can be written quickly

    enough down the serial cable. That is why we have had to cut out displaying stuff on the micro:bits

    LEDs which slows the whole process down.

    When you open the CSV file in

    Excel you will have some

    repeated readings taken

    before the discharge kicked in.

    So I have copied the data from

    row 24 downwards and pasted

    them in Columns D and E. But

    I want the timings to be

    readjusted to start at zero

    when the discharge started.

    So I have inserted an extra

    column between D and E, so

    that the voltages are moved to column F. In cell E1 I have written the formula `= D1 - $D$1’ to

    subtract the value in cell D1 from all each cell in that column. Copying the formula down column E

    produces the adjusted time. Now highlighting columns E and F we can produce a very nifty scatter

    graph indeed. With a right-click on the graph we can ask to fit a `trendline’. Select the first option,

    for an exponential fit and tick the boxes to show the formula and the value of R2. As you can see,

    the model is an amazingly good fit! So now we can export the data by copying columns E and F

    ready to paste into GeoGebra’s Spreadsheet View. Here is the result after doing 2-variable

    regression on columns A and B using an exponential model. The Graphic View has been set up to

    illustrate the idea of the `half-life’ of an exponential decay.

  • Point B is the intersection of the model y = g(x) with the y-axis. A is the origin. C is the midpoint of

    AB, D is mid-point of AC and E is mid-point of AD. Perpendiculars to the y-axis have been drawn

    through C, D, E to meet the curve at F, G, H. Perpendiculars to the x-axis have been drawn through

    F, G, H to meet the x-axis at I, J, K. The segments AI, IJ, JK have been constructed and measured.

    They are all of equal length. So this is a fundamental property of any negative exponential graph:

    the time taken to lose 50% of the current value is constant. This capacitor has a half-life of 0.78

    seconds.

    So the new features of MakeCode available in the App and the beta-version for browsers make

    data-capture much easier with micro:bits. By the way, the beta version for the web browser also

    includes a terminal emulator so you can see the data stream numerically as well as graphically.

    https://makecode.microbit.org/beta

  • The examples I have shown here have used a captive micro:bit for static experiments. Now we will

    look at using a pair of micro:bits where one can transmit sensed data wirelessly using `Radio’

    commands to the other which passes it over to MakeCode through the serial cable, thus achieving

    telemetry. We will start with a couple of simple experiments to establish the principles. We could

    write separate programs for the transmitter T and receiver R micro:bits, but with just a little

    ingenuity we can devise a single program that can be used in both devices.

    The `on start’ block

    just establishes the

    radio contact and

    sets both units into

    Listening mode.

    Pressing the `on

    button’ on R writes

    a number to the

    serial port to set the

    PC in listening mode

    and transmits a

    code number to T to

    prepare it to send back data. The `on radio received’ block does the work. If the received number

    is the 999 code, then it sends back an 888 code to tell R to get ready to receive. It pauses for 5

    seconds to let you set up things on the PC end so that you can set up `Show Data Device’. Then it

    just transmits the numbers 0 to 99. If the received number is the 888 code, then it tells R to get

    ready. Otherwise the `item’ sent is the data to write to the PC. Here is the graph recorded from

    the simulator.

  • So the next step is to test it with some sensor data. All we

    need do is to transmit some sensed data, such as acceleration,

    from T to R. Again we test this out on the simulator by using

    the mouse to wobble the T device on screen.

    So now we can download the same code to two micro:bits T and R. T can then put into motion

    remotely and it will send data to R which is connected to a PC with a serial cable. Of course we may

    want to send more than 100 data items, and to use a different sampling rate. These can easily be

    adjusted in the `for index’ loop. Here is a simple jiggle experiment.

    For the real experiment I am using a heavy wooden model elephant

    suspended from a door frame on a strong metal spring. The micro:bit T is

    attached with elastic bands and the system is set in motion up and down.

  • Here is the graph of the data transferred wirelessly from T to R, and then

    via the USB cable to MakeCode. With the data downloaded to the PC as a

    CSV file we can use Excel to tidy the data up a bit to remove the noisy

    beginning. Here we can see that the vertical accelerations vary between

    800 and 1200 units, with a mean just below 1000.

    This time the experiment has captured periodic data

    for approximately simple harmonic motion SHM,

    which can modelled by a sine graph. But there is not

    a sinusoidal option for the trend line in Excel. So

    once again we can copy and paste the data into

    GeoGebra for more detailed analysis.

    The `2-variable

    regression’ function in

    GeoGebra does offer a

    sine option, as shown. In

    order to improve the

    readability it makes

    sense to rescale the y-

    data. At rest the

    elephant has an

    acceleration due to

    gravity g of about 9.81

    ms-2. The micro:bit uses

    integer arithmetic, so the

    value translates to 981

    units. So column C uses formulae such as `C1 = (B1-981)/100’. Here is the re-scaled graph.

    A pretty impressive result, thanks to the power of micro:bit, MakeCode, Excel and GeoGebra!