About the Author
Les is a maker and trainer who has worked with the Raspberry Pi Foundation and the BBC to deliver computing training.
Magnets are wonderful things to experiment with and in this project, we shall use a magnet to alter the built-in compass of the micro:bit. Changing where it believes North will be and using it to create a simple alarm.
Parents: Please note that children should only use fridge magnets and not rare earth/neodymium magnets as they can be harmful if swallowed.
For this project, we shall be using the Javascript Blocks Editor https://microbit.org/code/ and we should already be comfortable copying code to our micro:bit.
When our micro:bit starts up we need to test that our compass is working, and so we use a repeat 4 times loop found in the Loops section.
We can find the compass heading block in Inputs. Drag the block over. But how can we use it? We need to use a block to scroll it across the micro:bit.
Inside of the repeat loop we use the Show Number block from Basic to scroll the compass heading across the micro:bit. This tests that our compass is working.
From Logic, we need to grab the ”if true then..else” block and place it inside the forever block. This will check to see if a certain condition has been met.
From Logic we use the “0 < 0” and place it over “true”, then we use another “compass heading” block in the first 0 and change the other to 200.
Compass headings can be between 0 and 360, the value 200 found using the startup script and noting the normal value. But if the value is below 200, then we show the surprised icon from Basic.
But if the alarm has not been triggered, then the magnet is still in place and so we use the else condition and another “show icon” block to show a happy face.
Here is the final code for the project, does it match yours?
Check for any bugs before downloading the code to your micro:bit.
The compass is located in the top right of the micro:bit, and when we use the magnet it alters where the micro:bit thinks magnetic north is so we can control the direction.
That’s it, now download the code to your micro:bit and when it has finished, move the magnet towards and away from the micro:bit and watch the screen change.
Well done you have made your own magnetic alarm.
You can attach this to a door and add a speaker to make loud noises to scare away parents/pets/siblings. You can learn how to connect a speaker by reading Issue 2 where we make a countdown timer.