Introduction

A reed switch is an electrical switch which is operated when a magnetic field is brought near to it. 

In this guide, you will learn how to connect it to the micro:bit and turn an LED as well as an alarm on and off. We will then test it with a magnet.

Complete this guide and use it to create a security alarm system. Most alarm systems use a magnetic reed switch on doors and windows. They may come in different forms and styles, but they operate using the same principle!
    • The reed switch module has three pins:

      Digital Output (DO)

      GND: In electronics, we define a point in a circuit to be a kind of zero volts or 0V reference point, on which to base all other voltage measurements. This point is called  ground or GND.

      3.3V  :  'VCC' stands for Voltage Common Collector. We'll connect the VCC pin to 3.3V on the micro:bit

    • Voltage is the difference in potential between two points. As it is difficult to talk about voltage without a reference point, we need another point to compare it to. 

  1. let signal = 0
    pins.setPull(DigitalPin.P1, PinPullMode.PullUp)
    basic.forever(function () {
        signal = pins.digitalReadPin(DigitalPin.P1)
        if (signal == 0) {
            music.playTone(262, music.beat(BeatFraction.Whole))
            basic.showIcon(IconNames.Angry)
            basic.showNumber(signal)
        } else if (signal == 1) {
            basic.showIcon(IconNames.Heart)
            basic.showNumber(signal)
        }
    })
    
    • Let's get started with programming the micro:bit using MakeCode editor

    • Click on 'New Project'

    • Copy and paste the following code into the Javascript interface

  2. let signal = 0
    pins.setPull(DigitalPin.P1, PinPullMode.PullUp)
    basic.forever(function () {
        signal = pins.digitalReadPin(DigitalPin.P1)
        if (signal == 0) {
            music.playTone(262, music.beat(BeatFraction.Whole))
            basic.showIcon(IconNames.Angry)
            pins.digitalWritePin(DigitalPin.P2, 1)
            basic.pause(500)
            pins.digitalWritePin(DigitalPin.P2, 0)
            basic.pause(500)
        } else {
            basic.showIcon(IconNames.Heart)
        }
    })
    
    • Now let's make the LED blink. Copy and paste this code into the Javascript interface, replacing the previous code.

    • Connect the micro:bit to your computer using a microUSB cable

    • Click on the 'Download' button in MakeCode editor

    • Find the downloaded hex file in your Downloads folder

    • Open up Finder on the MacOS or Explorer on Windows, and drag the hex file into MICROBIT under 'Devices' on the macOS.

    • Let the micro:bit blink as the program uploads to completion.