Raspberry Pi - Button Control Electromagnetic Lock
The tutorial instructs you how to use an Raspberry Pi and a button to control an electromagnetic lock. When the button is pressed, Raspberry Pi deactivates the electromagnetic lock for a predefined time (e.g. 10 seconds) to unlock the door. After that, the electromagnetic lock will be activated again to lock the door.
Or you can buy the following sensor kits:
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.
If you are unfamiliar with electromagnetic locks and buttons (including pinout, operation, and programming information), the following tutorials can help:
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:
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.
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
import RPi.GPIO as GPIO
import time
BUTTON_PIN = 18
RELAY_PIN = 16
GPIO.setmode(GPIO.BCM)
GPIO.setup(BUTTON_PIN, GPIO.IN, pull_up_down=GPIO.PUD_UP)
GPIO.setup(RELAY_PIN, GPIO.OUT)
prev_button_state = GPIO.HIGH
try:
GPIO.output(RELAY_PIN, GPIO.HIGH)
while True:
button_state = GPIO.input(BUTTON_PIN)
if button_state == GPIO.LOW and prev_button_state == GPIO.HIGH:
print("The button is pressed")
GPIO.output(RELAY_PIN, GPIO.LOW)
print("The door is unlocked")
time.sleep(5)
GPIO.output(RELAY_PIN, GPIO.HIGH)
print("The door is locked again")
prev_button_state = button_state
except KeyboardInterrupt:
print("Exiting...")
GPIO.cleanup()
python3 button_electromagnetic_lock.py
The script runs in an infinite loop continuously until you press Ctrl + C in the terminal.
Check out the line-by-line explanation contained in the comments of the source code!