Build a Raspberry Pi‑Powered Smart Door Lock with Python and MQTT

Ever walked up to your front door, fumbled for a key, and thought “there’s got to be an easier way”? You’re not alone. With a Pi, a bit of Python, and MQTT, you can turn that old deadbolt into a smart lock you control from your phone, voice assistant, or even a simple web page. This is exactly the kind of project I love sharing on PiIoT Lab, and it’s perfect for anyone who wants a quick win in home automation.

What You’ll Need

Before we dive in, let’s list the parts. I keep the list short so you can grab everything in one go.

  • Raspberry Pi (any model with GPIO works, but I use a Pi 4)
  • 5 V relay module (to drive the lock’s solenoid)
  • 12 V electric strike or solenoid lock
  • Power supply for the lock (usually 12 V, separate from the Pi)
  • Breadboard and jumper wires
  • Small push‑button (optional, for manual override)
  • MQTT broker (I use Mosquitto on the same Pi, but you can use a cloud broker)

That’s it. No fancy shields, no custom PCBs. If you have a spare Pi lying around, you’re already halfway there.

Wiring the Lock – Keep It Simple

First, connect the relay’s IN pin to a GPIO pin on the Pi, say GPIO 17. The relay’s COM (common) goes to the negative side of the lock’s power supply, and the NO (normally open) goes to the lock’s negative lead. The lock’s positive lead connects straight to the 12 V supply.

Pi GPIO17 ----> Relay IN
Relay COM ----> 12V - (ground)
Relay NO  ----> Lock -
Lock + ----> 12V +

If you add a push‑button, wire it between 3.3 V and another GPIO (e.g., GPIO 27) with a pull‑down resistor. That way you can unlock the door locally if the network is down.

Safety tip: The lock draws a few hundred milliamps. Keep the Pi’s power separate from the lock’s 12 V supply to avoid any accidental brown‑outs.

Setting Up MQTT

MQTT is a lightweight messaging protocol that works great for IoT. On PiIoT Lab we love it because it’s easy to set up and runs on almost any device.

  1. Install Mosquitto on the Pi:
sudo apt update
sudo apt install -y mosquitto mosquitto-clients
  1. Start the broker (it runs automatically after install). Test it with a simple publish/subscribe:
# In one terminal, listen for messages
mosquitto_sub -t "piiotlab/door"

# In another terminal, send a test message
mosquitto_pub -t "piiotlab/door" -m "test"

If you see “test” appear in the first terminal, you’re good to go. The topic piiotlab/door is our channel for lock commands. Feel free to change the name, but keep it consistent in the code.

Python Code – The Heart of the Lock

Now for the fun part. We’ll write a tiny Python script that subscribes to the MQTT topic and toggles the relay when it receives a command.

#!/usr/bin/env python3
import paho.mqtt.client as mqtt
import RPi.GPIO as GPIO
import time

# ----- Config -----
MQTT_BROKER = "localhost"
MQTT_TOPIC = "piiotlab/door"
RELAY_PIN = 17          # GPIO pin connected to relay IN
BUTTON_PIN = 27        # Optional manual button
UNLOCK_TIME = 5        # Seconds the lock stays open
# ------------------

GPIO.setmode(GPIO.BCM)
GPIO.setup(RELAY_PIN, GPIO.OUT, initial=GPIO.LOW)
GPIO.setup(BUTTON_PIN, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)

def unlock():
    print("Unlocking door")
    GPIO.output(RELAY_PIN, GPIO.HIGH)   # Activate relay
    time.sleep(UNLOCK_TIME)
    GPIO.output(RELAY_PIN, GPIO.LOW)    # Deactivate relay
    print("Door locked again")

def on_connect(client, userdata, flags, rc):
    print("Connected to MQTT broker")
    client.subscribe(MQTT_TOPIC)

def on_message(client, userdata, msg):
    payload = msg.payload.decode().strip().lower()
    if payload == "unlock":
        unlock()
    else:
        print(f"Ignored message: {payload}")

def button_callback(channel):
    print("Manual button pressed")
    unlock()

# Set up MQTT client
client = mqtt.Client()
client.on_connect = on_connect
client.on_message = on_message

client.connect(MQTT_BROKER, 1883, 60)

# Set up button interrupt
GPIO.add_event_detect(BUTTON_PIN, GPIO.RISING, callback=button_callback, bouncetime=300)

try:
    client.loop_forever()
except KeyboardInterrupt:
    print("Shutting down")
finally:
    GPIO.cleanup()

Save this as smart_lock.py and make it executable:

chmod +x smart_lock.py

Run it with sudo ./smart_lock.py. The script does three things:

  1. Listens for MQTT messages on piiotlab/door.
  2. When it receives the word “unlock”, it powers the relay for a few seconds.
  3. Monitors the manual button and does the same when you press it.

Controlling the Lock from Anywhere

Now that the Pi is listening, you can send a command from any device that can reach your MQTT broker. Here’s a quick example using a phone app:

  • Install MQTT Dashboard (available on Android and iOS).
  • Add a new connection pointing to your home IP address (or use a dynamic DNS name).
  • Create a button that publishes “unlock” to piiotlab/door.

Press the button, and the lock should click open. If you have a voice assistant like Home Assistant, you can integrate the same MQTT topic and say “Hey Google, unlock the front door”.

Securing Your Smart Lock

A smart lock is only as safe as the network it runs on. Here are a few low‑effort steps that make a big difference:

  • Change the default MQTT password. Edit /etc/mosquitto/passwd and add a strong password.
  • Use TLS if you expose the broker to the internet. Mosquitto supports Let's Encrypt certificates.
  • Limit who can publish to the piiotlab/door topic by setting ACLs in Mosquitto’s config.

Even a simple password change cuts out the “anyone on my Wi‑Fi can unlock my door” scenario.

Testing and Troubleshooting

When you first try it, you might see the relay click but the lock stay closed. Common culprits:

  • Power mismatch – make sure the lock’s 12 V supply can deliver enough current (check the spec, usually 300‑500 mA).
  • Relay wiring – the relay must be wired to the lock’s ground side, not the positive side.
  • GPIO pin mode – double‑check that you set the correct BCM pin number in the script.

If the Pi doesn’t connect to MQTT, verify that the broker is running (systemctl status mosquitto) and that the Pi’s firewall isn’t blocking port 1883.

Wrap‑Up

That’s it! In under an hour you’ve turned a regular deadbolt into a network‑controlled smart lock using a Raspberry Pi, Python, and MQTT. The whole thing lives on PiIoT Lab, where I love sharing projects that blend hardware and code without a lot of fluff.

Feel free to tweak the unlock time, add a keypad, or hook it up to a fingerprint sensor. The sky’s the limit, but the core idea stays the same: a tiny computer, a simple script, and a reliable messaging protocol can make everyday life a little smoother.

Happy hacking, and may your doors always open when you want them to.

Reactions
Do you have any feedback or ideas on how we can improve this page?