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):
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:
import RPi.GPIO as GPIO
GPIO.setmode(GPIO.BCM) # GPIO Numbers instead of board numbers
MAGNET_GPIO = 17
GPIO.setup(MAGNET_GPIO, GPIO.IN) # GPIO Assign mode
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:
GPIO.add_event_detect(MAGNET_GPIO, GPIO.BOTH, callback=my_callback)
In this case, a function called
my_callback() must be present, which is then called. Here are the states
GPIO.FALLING instead of