Raspberry Pi - Door Sensor

The door sensor is a common feature in security systems. It is used to detect and monitor entrances, such as doors and windows. This device is also referred to as an contact sensor, entry sensor, or window sensor.

This tutorial instructs you how to use Raspberry Pi with the door sensor. In detail, we will learn:

Hardware Preparation

1×Raspberry Pi 4 Model B
1×Door Sensor
1×(Optional) Screw Terminal Block Shield for Raspberry Pi
1×(Optional) USB-C Power Cable with On/Off Switch for Raspberry Pi 4B
1×(Optional) Plastic Case and Cooling Fan for Raspberry Pi 4B
1×(Optional) HDMI Touch Screen Monitor for Raspberry Pi

Or you can buy the following sensor kits:

1×DIYables Sensor Kit (30 sensors/displays)
1×DIYables Sensor Kit (18 sensors/displays)
Disclosure: Some of the links provided in this section are Amazon affiliate links. We may receive a commission for any purchases made through these links at no additional cost to you.
Additionally, some of these links are for products from our own brand, DIYables.

Overview of Door Sensor

The Door Sensor Pinout

A door sensor consists of two parts:

  • A reed switch with two pins
  • A magnet
Door Sensor pinout

Similar to a typical switch/button, there is no requirement to differentiate between the two pins of the reed switch.

How It Works

The magnet is affixed to the door/window, which is the movable element, and the reed switch is attached to the door frame, which is the stationary element. When the door is shut, the two components are in contact:

  • When the magnet is close to the reed switch, the reed switch circuit is closed
  • When the magnet is distant from the reed switch, the reed switch circuit is open
Door Sensor How It Works pinout

※ NOTE THAT:

The reed switch does not provide LOW or HIGH values on its pins. It is either closed or open. The value of the pin connected to Raspberry Pi can be LOW, HIGH, or a floating (unpredictable) value. To prevent the floating value, we must use a pull-up or pull-down resistor on the Raspberry Pi pin.

If we connect one pin of the reed switch to GND and the other pin of the reed switch to a Raspberry Pi input pin with a pull-up resistor (internal or external):

  • When the magnet is close to the reed switch, the value in the Raspberry Pi input pin is LOW
  • When the magnet is distant from the reed switch, the value in the Raspberry Pi input pin is HIGH

To find out the status of the door, we merely need to check the state of Raspberry Pi's input pin:

  • If the state is LOW, the door is closed
  • If the state is HIGH, the door is opened

To detect the door-opening/door-closing events, we can monitor the state change on the Raspberry Pi input pin:

  • If the state transitions from LOW to HIGH, the door-opening event is detected
  • If the state transitions from HIGH to LOW, the door-closing event is detected

Wiring Diagram

The wiring diagram between Raspberry Pi and Door Sensor

This image is created using Fritzing. Click to enlarge image

To simplify and organize your wiring setup, we recommend using a Screw Terminal Block Shield for Raspberry Pi. This shield ensures more secure and manageable connections, as shown below:

Raspberry Pi Screw Terminal Block Shield

How To Program For Door Sensor

  • Initialize the Raspberry Pi pin to digital input mode by utilizing the GPIO.setup() function. As an example, the following code can be used to initialize pin 13 as an input:
GPIO.setup(DOOR_SENSOR_PIN, GPIO.IN, pull_up_down=GPIO.PUD_UP)
  • Utilizes the GPIO.input() function to ascertain the status of the Raspberry Pi pin.
door_state = GPIO.input(DOOR_SENSOR_PIN)

Raspberry Pi Code - Check Door Open and Close State

Detailed Instructions

  • Make sure you have Raspbian or any other Raspberry Pi compatible operating system installed on your Pi.
  • Make sure your Raspberry Pi is connected to the same local network as your PC.
  • Make sure your Raspberry Pi is connected to the internet if you need to install some libraries.
  • If this is the first time you use Raspberry Pi, See how to set up the Raspberry Pi
  • Connect your PC to the Raspberry Pi via SSH using the built-in SSH client on Linux and macOS or PuTTY on Windows. See to how connect your PC to Raspberry Pi via SSH.
  • Make sure you have the RPi.GPIO library installed. If not, install it using the following command:
sudo apt-get update sudo apt-get install python3-rpi.gpio
  • Create a Python script file door_sensor.py and add the following code:
""" This Raspberry Pi code was developed by newbiely.com This Raspberry Pi code is made available for public use without any restriction For comprehensive instructions and wiring diagrams, please visit: https://newbiely.com/tutorials/raspberry-pi/raspberry-pi-door-sensor """ import RPi.GPIO as GPIO import time # Set the GPIO mode to BCM GPIO.setmode(GPIO.BCM) # Define the GPIO pin number to which the sensor is connected DOOR_SENSOR_PIN = 16 # Setup the GPIO pin as an input GPIO.setup(DOOR_SENSOR_PIN, GPIO.IN, pull_up_down=GPIO.PUD_UP) try: while True: # Read the state of the door sensor (HIGH when open, LOW when closed) door_state = GPIO.input(DOOR_SENSOR_PIN) if door_state == GPIO.HIGH: print("Door is OPEN") else: print("Door is CLOSED") time.sleep(0.1) # Add a small delay to avoid excessive reads except KeyboardInterrupt: print("Exiting...") GPIO.cleanup()
  • Save the file and run the Python script by executing the following command in the terminal:
python3 door_sensor.py
  • Bring the magnet close to the reed switch, then move it away.
  • Check the result on the Terminal.
PuTTY - Raspberry Pi
Door is OPEN Door is OPEN Door is OPEN Door is CLOSED Door is CLOSED Door is CLOSED Door is CLOSED Door is CLOSED Door is OPEN Door is OPEN

The script runs in an infinite loop continuously until you press Ctrl + C in the terminal.

You will be noticed that the code keeps printing the current state of the door. If you want to print the door state only when it changes, check out the next session.

Raspberry Pi Code - Detect Door-opening and Door-closing Events

  • Create a Python script file door_sensor_events.py and add the following code:
""" This Raspberry Pi code was developed by newbiely.com This Raspberry Pi code is made available for public use without any restriction For comprehensive instructions and wiring diagrams, please visit: https://newbiely.com/tutorials/raspberry-pi/raspberry-pi-door-sensor """ import RPi.GPIO as GPIO import time # Set the GPIO mode to BCM GPIO.setmode(GPIO.BCM) # Define the GPIO pin number to which the sensor is connected DOOR_SENSOR_PIN = 17 # Setup the GPIO pin as an input GPIO.setup(DOOR_SENSOR_PIN, GPIO.IN, pull_up_down=GPIO.PUD_UP) # Variable to store the previous state of the door sensor prev_door_state = GPIO.HIGH try: while True: # Read the state of the door sensor (HIGH when open, LOW when closed) door_state = GPIO.input(DOOR_SENSOR_PIN) if door_state != prev_door_state: if door_state == GPIO.HIGH: print("Door is OPEN") else: print("Door is CLOSED") prev_door_state = door_state time.sleep(0.1) # Add a small delay to avoid excessive reads except KeyboardInterrupt: print("Exiting...") GPIO.cleanup()
  • Save the file and run the Python script by executing the following command in the terminal:
python3 door_sensor_events.py
  • Bring the magnet close to the reed switch, then move it away.
  • Check the result on the Terminal.
PuTTY - Raspberry Pi
Door is OPEN Door is CLOSED
  • You will see that the state of the door is printed only when the state changes

Video Tutorial

※ OUR MESSAGES

  • As freelancers, We are AVAILABLE for HIRE. See how to outsource your project to us
  • Please feel free to share the link of this tutorial. However, Please do not use our content on any other websites. We invested a lot of effort and time to create the content, please respect our work!