Raspberry Pi - Door Sensor - Relay

This tutorial instructs you how to use the Raspberry Pi and door sensor to control the relay. By connecting the relay to a soleniod lock, light bulb, LED strip, motor, or actuator..., we can use a door sensor to control the them. We will learn two different applications:

Application 1 - The relay is activated when door is open and the relay is deactivated when door is closed. The relay state is synchronized with the door sensor state. In detail:

Application 2 - The relay state is toggled each time the door is opened. More specifically:

Hardware Preparation

1×Raspberry Pi 4 Model B
1×Door Sensor
1×Relay
1×Breadboard
1×Jumper Wires
1×(Optional) Solenoid Lock
1×(Optional) 12V Power Adapter
1×(Optional) DC Power Jack
1×(Optional) Screw Terminal Adapter for Raspberry Pi

Or you can buy the following sensor kit:

1×DIYables Sensor Kit 30 types, 69 units
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. We appreciate your support.

Overview of Relay and Door Sensor

If you are unfamiliar with relay and door sensor (including pinout, operation, and programming), the following tutorials can help:

Wiring Diagram

The wiring diagram between Raspberry Pi and Door Sensor relay

This image is created using Fritzing. Click to enlarge image

Application 1 - The relay state is in sync with the door sensor 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_relay.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-relay import RPi.GPIO as GPIO # Set the GPIO mode (BCM or BOARD) GPIO.setmode(GPIO.BCM) # Define the GPIO pin number to which the relay is connected RELAY_PIN = 20 # Define the GPIO pin number to which the door sensor is connected DOOR_SENSOR_PIN = 18 # Set up the GPIO pins GPIO.setup(DOOR_SENSOR_PIN, GPIO.IN, pull_up_down=GPIO.PUD_UP) # Input with pull-up resistor GPIO.setup(RELAY_PIN, GPIO.OUT) # Output try: while True: door_state = GPIO.input(DOOR_SENSOR_PIN) if door_state == GPIO.HIGH: print("The door is open") GPIO.output(RELAY_PIN, GPIO.HIGH) # Turn the relay on else: print("The door is closed") GPIO.output(RELAY_PIN, GPIO.LOW) # Turn the relay off except KeyboardInterrupt: GPIO.output(RELAY_PIN, GPIO.LOW) # Turn off the relay GPIO.cleanup()
  • Save the file and run the Python script by executing the following command in the terminal:
python3 door_sensor_relay.py
  • Open and close the door
  • Check out the change in the relay's condition. You will see that the relay state is in sync with the door sensor state.

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

Code Explanation

Check out the line-by-line explanation contained in the comments of the source code!

Application 2 - Door Sensor toggles Relay

Detailed Instructions

  • Create a Python script file door_toggle_relay.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-relay import RPi.GPIO as GPIO import time # Constants won't change DOOR_SENSOR_PIN = 18 # The number of the door sensor pin RELAY_PIN = 20 # The number of the relay pin # Variables will change relay_state = GPIO.LOW # The current state of the relay prev_door_state = GPIO.LOW # The previous state of the door sensor door_state = GPIO.LOW # The current state of the door sensor # Set up GPIO GPIO.setmode(GPIO.BCM) # Use BCM GPIO numbering GPIO.setup(RELAY_PIN, GPIO.OUT) # Initialize the relay pin as an output GPIO.setup(DOOR_SENSOR_PIN, GPIO.IN, pull_up_down=GPIO.PUD_UP) # Initialize the door sensor pin as a pull-up input try: while True: # Read the state of the door sensor value prev_door_state = door_state # Save the last state door_state = GPIO.input(DOOR_SENSOR_PIN) # Read new state if prev_door_state == GPIO.LOW and door_state == GPIO.HIGH: time.sleep(0.1) # 100 milliseconds debounce time print("The door is closed") # Toggle the state of the relay if relay_state == GPIO.LOW: relay_state = GPIO.HIGH else: relay_state = GPIO.LOW # Control relay according to the toggled state GPIO.output(RELAY_PIN, relay_state) except KeyboardInterrupt: # Clean up GPIO on program exit GPIO.cleanup()
  • Save the file and run the Python script by executing the following command in the terminal:
python3 door_toggle_relay.py
  • Open and close the door several times.
  • Check out the change in the relay's state. You'll notice that the relay will switch on or off one time whenever you open the door.

Video Tutorial