Skip to main content

09 April 2022

Datalogging with the micro:bit using Variables & Algorithms

CAS logo
Written by

Computing at School

The last post looked at how a variable can be used to store and display sensor data on a microbit. This post looks at how you can extend that concept, by using a simply algorithm to manipulate the data collected.

An algorithm is a sequence of instructions that are followed to complete a task. In this case the micro bit will automatically convert a temperature reading from Centigrade to Fahrenheit using a simple formula.

First create the code to capture a temperature reading from the microbit's temperature sensor. This is always a value in Centigrade. Store this reading as a value in a variable. Use button A to log this reading Use button B input to display the reading.

Add an show icon block to the on button A event block to show that the reading has been captured.

Next when both A and B buttons are pressed the microbit will convert the temperature value into a Fahrenheit value.
To convert any centigrade value in fahrenheit we use some simple maths. Simply multiply the value in centigrade by 1.8 and add 32. We are going to use some code to automatically do this.

Create a new variable, call this Fahrenheit. Add a Set Fahrenheit block to 0 to the on Start event block. Next add an On button pressed block and change this to A+B. Now add a set Fahrenheit to block to the On Button A+B pressed block. Now go to the Math command list and drag a multiplication command block into the space after the to . Got back to the Variable command list, find the temperature variable and drag this to replace the first zero in the multiplication block. Change the second zero in the block to 1.8. Drag another Set Fahrenheit to block, this time drag a addition block from the Math commands. Now drag the fahrenheit to replace the first zero. Change the second zero to 32.

Now when both buttons A+B are pressed the microbit will multiply the value stored in the variable temp by 1.8 and store this in the new variable fahrenheit. Next this value has 32 added to it and stored in the fahrenheit variable. The value is then displayed as the captured temperature as measured on the farhenheit scale. Pressing the B button will display the captured value in centigrade, as this value has not been changed and is still stored in the temp variable. It will only changed when a new reading is taken.

This activity is a great learning opportunity for students

Code available here > https://makecode.microbit.org/_hu56qLY6PLrb 

Discussion

Please login to post a comment