Activity

# Simple door alarm

Intermediate | MakeCode, Python | Buttons, Compass, LED display | Magnetism, Relational operators, Selection

## Step 1: Make it

### What is it?

Has anyone been in your room? With a micro:bit, a battery pack and a magnet you can make an alarm to alert you to sneaky snoopers...

### How it works

• In this project you'll make a door alarm that works just like a real door sensor in a home security system.
• Your micro:bit has a built-in compass sensor called a magnetometer. You can use it to measure the Earth’s magnetic field as a compass - or to sense how strong magnetic fields are much closer to home!
• Fix a magnet in the corner of a door and a micro:bit with the door alarm program close to it on the door frame like in the video.
• The program uses the micro:bit’s compass (magnetometer) input sensor and a forever loop to keep measuring the strength of the magnetic field.
• It uses selection so when it falls below a certain level (the threshold), it shows an angry face on the LED display. This means the magnet moved away from the micro:bit - when the door was opened - so someone may have been in your room!
• Pressing button A shows the current magnetic force reading. Use this to decide what threshold number to use by taking readings with the door open and closed. We used 200 in our example, but this depends on how strong your magnet is and if there are any other magnetic fields nearby. The coding video above shows you how to do this.
• Press button A to clear the angry face and reset the alarm.
• Note that when you first use the compass sensor you may have to calibrate it by playing a game to fill the screen with dots, like calibrating a mobile phone’s compass.

### What you need

• a micro:bit
• MakeCode online code editor
• battery pack
• magnet
• some way of fixing the magnet, micro:bit and battery pack to the door and door frame

## Step 2: Code it

``````1# Python uses nanoteslas to measure magnetism.
2# Experiment with different numbers depending on the
4# pressing button A.
5
6from microbit import *
7
8while True:
9    if button_a.was_pressed():
10        display.scroll(compass.get_field_strength())
11    if compass.get_field_strength() < 200000:
12        display.show(Image.ANGRY)
``````

## Step 3: Improve it

• Add a speaker and an audible alarm
• Use a variable to count the number of times your door has been opened - you'll need to add code to sense when it's been opened and closed
• Create a timer to measure how long a door has been left open