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 and we should already be comfortable copying code to our micro:bit.

Step 1 - Startup Screen

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.

Step 2 - Check your heading

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.

Step 3 - Show The Heading

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.

Step 4 - A Little Logic Goes A Long Way

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.

Step 5 - Checking values

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.

Step 6 - So what happens if...

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.

Step 7 - All Is Normal

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.

Step 8 - Final Code

Here is the final code for the project, does it match yours? Check for any bugs before downloading the code to your micro:bit.

Step 9 - Magnetic alarm

Program in action

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 and 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.