Step‑by‑Step Guide: Build a Raspberry Pi Smart Door Lock with Python
Ever walked up to a door, fumbled with keys, and thought “there’s got to be a better way”? In 2024 every maker is turning everyday objects into connected gadgets, and a smart lock is the perfect starter project. It teaches you hardware wiring, Python coding, and a bit of security thinking—all without breaking the bank. Let’s get that door talking to your Pi.
What You Need
| Item | Why it matters |
|---|---|
| Raspberry Pi (any model with GPIO, Pi Zero W works fine) | The brain of the lock. |
| 5 V relay module (single‑channel) | Lets the Pi control the lock’s power safely. |
| Electronic strike or solenoid lock (12 V typical) | The actual locking mechanism. |
| Power supply for the lock (12 V wall wart) | Keeps the lock strong enough to hold. |
| Micro‑USB or USB‑C power for the Pi | Powers the Pi itself. |
| Jumper wires, breadboard or small perf board | For tidy connections. |
| Optional: magnetic door sensor, keypad or RFID reader | Adds extra features later. |
All of these are cheap on sites like Pimoroni or Amazon. I bought a spare Pi Zero from a friend’s old project and a small 12 V strike that used to secure my garden shed. The first time I wired it, I accidentally shorted the relay—nothing burned, but the Pi rebooted a few times. That’s why I always double‑check the wiring before plugging in power.
Wiring the Lock
1. Connect the relay to the Pi
- VCC on the relay goes to 5 V pin on the Pi.
- GND on the relay goes to any ground pin.
- IN (control pin) on the relay goes to a free GPIO, e.g., GPIO 17 (pin 11).
2. Wire the lock to the relay
- Cut the positive wire of the 12 V lock supply.
- Connect one end to the COM (common) terminal of the relay.
- Connect the other end to the NO (normally open) terminal.
When the relay is off, the circuit is open and the lock stays locked. When the Pi drives the relay high, the circuit closes and the lock unlocks.
3. Power everything
- Plug the 12 V supply into the lock and relay.
- Plug the Pi’s own power supply into the Pi.
Never power the lock directly from the Pi’s 5 V rail—those pins can only supply a few hundred milliamps, far less than a solenoid needs.
Setting Up the Pi
Install the OS
If you haven’t already, flash Raspberry Pi OS Lite onto a micro‑SD card. I like the Lite version because it’s headless—no desktop clutter, just a terminal. Boot the Pi, SSH in, and run:
sudo apt update
sudo apt upgrade -y
Enable GPIO Access
The default Pi OS already includes the gpio library, but we’ll use the Python RPi.GPIO package for clarity:
sudo apt install python3-rpi.gpio -y
Secure the Pi
Change the default password, enable the firewall (ufw), and consider setting up a static IP so you can reach the lock reliably. A quick sudo raspi-config gets you through most of that.
Writing the Python Code
Create a new file called smart_lock.py in your home folder.
#!/usr/bin/env python3
import RPi.GPIO as GPIO
import time
# Pin where the relay is connected
RELAY_PIN = 17
# Setup
GPIO.setmode(GPIO.BCM) # Use Broadcom pin numbers
GPIO.setup(RELAY_PIN, GPIO.OUT) # Set pin as output
GPIO.output(RELAY_PIN, GPIO.LOW) # Start with lock engaged
def unlock(duration=5):
"""Open the lock for *duration* seconds."""
print("Unlocking door...")
GPIO.output(RELAY_PIN, GPIO.HIGH) # Relay closes, lock opens
time.sleep(duration)
GPIO.output(RELAY_PIN, GPIO.LOW) # Relay opens, lock closes
print("Door locked again.")
if __name__ == "__main__":
try:
while True:
cmd = input("Enter 'open' to unlock, 'quit' to exit: ").strip().lower()
if cmd == "open":
unlock()
elif cmd == "quit":
break
finally:
GPIO.cleanup()
How it works
- GPIO.setmode(GPIO.BCM) tells the library to use the chip’s pin numbers rather than the board layout.
- GPIO.setup(..., GPIO.OUT) makes the pin an output so we can drive the relay.
- GPIO.HIGH energizes the relay coil, closing the contacts and powering the lock.
- GPIO.LOW turns the coil off, opening the contacts and re‑locking.
The script waits for you to type “open” on the console, then unlocks for five seconds. You can change the duration argument or add a keypad read later.
Testing and Tweaking
Run the script with python3 smart_lock.py. When you type open, you should hear a click as the strike releases. If nothing happens:
- Verify the relay LED lights when you type
open. - Check the wiring on the COM/NO terminals—swap them if the lock stays locked.
- Make sure the 12 V supply is actually delivering voltage (use a multimeter).
If the lock stays unlocked after the script finishes, the relay may be stuck. Some cheap relays have a “latch” mode; a quick tap on the relay’s coil pins can release it, but it’s better to buy a quality module with a built‑in flyback diode.
Putting It All Together
Now that the basic unlock works, you can add a few practical touches:
- Web Interface – Use Flask to create a tiny web page that sends a request to the Pi. A single button press on your phone can open the door.
- Door Sensor – A magnetic reed switch tells the Pi whether the door is closed. Combine it with the unlock routine so the lock never stays open when the door is ajar.
- Authentication – Add a keypad, RFID reader, or even a facial‑recognition script. The Pi can verify the input before calling
unlock().
I started with just the console script, then added a Flask page for my front door. The first time a delivery driver used the QR code on my porch to open the lock, I felt like a sci‑fi director—except the “door” was my actual front door, not a movie set.
Safety and Best Practices
- Never leave the lock powered continuously unless you need it. A short power outage can leave the door stuck. Use a UPS or a battery backup if you live in an area with flaky power.
- Secure the Pi physically. A small case with a screw mount prevents tampering.
- Encrypt any network traffic if you expose the lock to the internet. Use HTTPS and strong passwords; a door that can be opened over Wi‑Fi is a tempting target for hackers.
With these steps, you have a functional smart lock that you built yourself. The joy of hearing the strike click on command is worth every solder joint and line of Python. Keep experimenting, share your tweaks on the PiIoT Lab community, and remember: the best projects are the ones that solve a real need in your daily life.
- → Step-by-Step Guide: Build a Raspberry Pi Smart Light Switch for Under $30 @techandtinker
- → DIY Guide: Create a Modular IoT Sensor System for Your Smart Home Using Sensor Blocks @sensorblocks
- → Automate Your Garden Irrigation Using Raspberry Pi and MQTT: A Complete DIY Guide @smarthomecrafts
- → DIY Home Security: Build a Low-Cost Smart Camera System Using Raspberry Pi and Home Assistant @smarthomeharmony
- → Step‑by‑Step Guide to Building a Voice‑Controlled Lighting System on a Budget @smarthomeinsights