Build a Raspberry Pi door / window sensor with Reed Relais

In addition to a surveillance camera and motion sensors, information about open windows and doors is also of interest to a self-built surveillance system. A check with infrared light barriers or other methods would certainly be possible, but in this case, that is much more complicated.

In this tutorial, it will be shown how to easily check the e.g. status of the window with a magnetic switch.

Required Hardware Parts

Luckily, not much is needed to attach the switch, and most parts are likely already present in most hobbyists crates. I have used these components:


The setup is as shown in the picture. As input pin I used GPIO 17 (board pin 11):

magnet contact breadboard

magnetic switches

The wired module allows the voltage to flow through the associated magnet.

It does not matter which of the two cables of the magnetic switch is connected to the base of the transistor. The free end should be attached to the window/door and the one with cable best to the fixed door/window frame.

If the two parts are too far apart, it is possible that only a very small amount of electricity will flow through the transistor, which is insufficient to switch. In this case, you can try making a Pi’s connection 5V instead of 3.3V, but then you should definitely set a resistance between the transistor emitter and GPIO.

Of course, you could build this circuit as a pull-up resistor and thus would have a HIGH signal only when the window is open.


The controls are very simple and can be used in this form in many projects. Instead of my subsequent Python code, similar code can also be used e.g. in C ++ (using WiringPi).

But now to the code:

sudo python

As long as the window and thus also the magnetic switch is closed, a 1 is displayed on the pin. As soon as the contact is interrupted, the transistor no longer switches and a zero is displayed on the GPIO. This will allow you to query if a window/door is opened or not.

If you want to wait for the state to change, you can use the following function:

In this case, a function called my_callback() must be present, which is then called. Here are the states GPIO.RISING and GPIO.FALLING instead of GPIO.BOTH possible.

Bild: Toby Golding/Flickr(CC BY 2.0)

Leave a Reply

Your email address will not be published. Required fields are marked *