In this lesson we will turn our microbits into a compass and thermometer by programming the buttons to use the sensors.
Go to the makecode.com website and create a new Microbit project.
Go to the Makecode.com Microbit website using the link below and click on the 'New Project' button underneath the 'My Projects' heading.
Install the micro:bit app on your iPad or tablet.
Open the app, tap 'Create code' and then create a new project.
Our microbits have a compass in them that can tell your direction with respect to the North Magnetic Pole. We're going to create a variable to store your direction (in degrees) and in a later step we will display N (for north), S (for south), E (for east) or W (for west) depending on what direction the microbit is pointing in.
In the Variables toolbox, create a new variable by clicking the 'Make a Variable' button.
In the Variables toolbox, create a new variable by clicking the 'Make a Variable' button.
Once you click this button a box will appear asking what you want to call your variable. Give it a name that reminds you what you will be using it for. For example, if you wanted to keep track of your score in a game, you would create a variable called 'score'.
Now add the following code to set the 'direction' variable equal to the current reading of the microbit's compass.
basic.forever(function () { direction = input.compassHeading() })
We use the 'forever' block as we continually want to keep checking the compass heading and setting the 'direction' variable equal to it.
Next we need to program our microbit to tell us if the direction we're facing is North, South, East or West. We're going to do this when you press the A button and we will need an 'if then else' block to test what direction we're pointing in. Add the following code:
input.onButtonPressed(Button.A, function () { if (true) { } else if (false) { } else if (false) { } else { } })
Note you will need to click the + button twice on the 'if then else' block. This adds extra 'else if' lines into the block.
We modify the 'if then else' block so that we can test for 3 conditions (for North, East and South) and the else part will be used for West.
Now we will fill out the 'if then else' block to check which direction the microbit is pointing in and display North, South, East or West.
Direction | Display |
---|---|
is greater than or equal to 315 | N |
is less than 135 | E |
is less than 225 | S |
otherwise it must be between 225 and 314 | W |
Using the blocks in the Basic, Logic and Variables toolboxes, add the following code to the 'if then else' block:
input.onButtonPressed(Button.A, function () { if (direction >= 315 || direction < 45) { basic.showString("N") } else if (direction < 135) { basic.showString("E") } else if (direction < 225) { basic.showString("S") } else { basic.showString("W") } })