Raspberry Pi Home Automation Project

Smart Home with RFID Lock + Auto Light & Fan | Raspberry Pi Kids Project | MakeMindz
🔐 Raspberry Pi Home Automation Project

Build a Smart Home
with RFID Lock + Auto Light & Fan

Tap your RFID card to unlock the door, then watch the lights and fan turn on and off all by themselves — a real smart home, built by you!

RFIDCard Door Lock
AutoLight + Fan
~₹1800Total Cost
4 hrsBuild Time
MediumDifficulty

The Big Idea

How Does a Smart Home Work? 🤔

🪪

The RFID Card is a Digital Key!

Just like a metal key fits into a lock, an RFID card has a tiny chip with a unique ID number. When you tap it near the reader, it "whispers" its secret number using radio waves. If the Raspberry Pi recognizes that number on its approved list, the door unlocks!

🌗

The Light Sensor is Like Your Eyes Adjusting to Darkness

An LDR (Light Dependent Resistor) changes its electrical resistance based on how much light hits it — bright room = low resistance, dark room = high resistance. Raspberry Pi reads this value and automatically switches the light ON when it gets dark, just like how you'd flip a switch yourself!

🌡️

The Temperature Sensor Decides When You Need the Fan

A temperature sensor constantly measures the room's warmth. When it gets too hot — say above 30°C — Raspberry Pi tells a relay (an electronic switch) to turn the fan ON automatically. No need to get up and switch it on yourself!

Three Smart Modules in One Home 🧩

🔐
RFID Door Lock
Only approved cards open the door — like a secret password for your house!
RC522 + Servo
💡
Automatic Light
Turns on by itself when the room gets dark, and off when it's bright again.
LDR Sensor
🌀
Automatic Fan
Switches on automatically when the room gets too warm, keeping things cool.
Temp Sensor + Relay

Shopping List

Parts You'll Need 🛒

All available at electronics shops or online stores like Robu.in, Robocraze, or Amazon. Ask a parent or teacher to help you buy them!

🎛️
Raspberry Pi (3B+/4)
× 1 — The brain
📶
RC522 RFID Reader + Cards
× 1 set — Door access
⚙️
SG90 Micro Servo Motor
× 1 — Door lock latch
🌗
LDR Sensor Module
× 1 — Light detection
🌡️
DHT11 Temperature Sensor
× 1 — Heat detection
🔌
2-Channel Relay Module
× 1 — Controls light & fan
💡
Small LED Bulb / Light
× 1 — Room light
🌀
Small DC Fan (5V)
× 1 — Room fan
📺
SSD1306 OLED Display (optional)
× 1 — Status screen
🔔
Buzzer (5V)
× 1 — Access denied alert
🧱
Breadboard
× 1 — Wiring base
🌈
Female-to-Male Jumper Wires
× 25 — For GPIO
📦
Cardboard House Model
for the build
💻
MicroSD Card (8GB+) with Raspberry Pi OS
× 1 — Pi's storage
💡

Why Raspberry Pi instead of Arduino? Raspberry Pi is a tiny full computer — it can run Python easily, connect to WiFi, and handle multiple sensors at once (RFID + temperature + light) without needing extra modules. That makes it perfect for a multi-feature smart home project!


Phase 01

Building the Model House 🏗️

1

Prepare a sturdy cardboard box

Use a medium-to-large cardboard box as the house shell. Cut out a front door opening and a window opening on one side.

2

Build the swinging door

Cut a door-shaped piece of cardboard slightly smaller than the opening. Attach it to the servo's rotating arm using a thin rod or stiff wire so the servo can swing it open and shut.

3

Mount the RFID reader near the door

Fix the RC522 reader on the outside wall next to the door, at a height where a card can be tapped easily — like a real smart doorbell panel!

4

Add two "rooms" inside

Use a cardboard divider to split the inside into two sections. Mount the LED bulb in one room's ceiling and the small fan in the other room's ceiling.

5

Place sensors in the right spots

Mount the LDR sensor near the window (so it can sense outside light) and the temperature sensor inside the fan's room (so it can sense room heat).

6

House the Raspberry Pi outside the model

Keep the Raspberry Pi, relay module, and breadboard mounted on a small board next to (or behind) the house model, with wires running through small holes into each room.

This is a model, not real mains wiring! Our project uses low-voltage 5V components only (LED bulb, small DC fan). Never connect this project to real household electricity (220V/110V) — that requires a licensed electrician and proper safety equipment!


Phase 02

Circuit Diagram & Wiring

Safety first! Always shut down and unplug the Raspberry Pi before changing any wires. RFID reader uses SPI communication — double-check pin positions carefully, as wrong wiring can damage the GPIO pins!

RASPBERRY PI 5V GND GPIO8 (CE0) GPIO10(MOSI) GPIO9 (MISO) GPIO11(SCLK) GPIO25(RST) GPIO18 (Servo) GPIO4 (DHT11) GPIO17 (LDR) GPIO22 (Relay1-Light) GPIO23 (Relay2-Fan) GPIO27 (Buzzer) RC522 RFID Card Reader 3V3 GND MOSI MISO SCK RST LDR Light Sensor DHT11 Temp Sensor SG90 SERVO Door Lock 2-CH RELAY CH1-Light CH2-Fan 💡 LIGHT 🌀 FAN BUZZER COMMON GROUND RAIL WIRE LEGEND Power 5V/3.3V GND SPI / Signal Relay Control Servo Signal Sensor Data

Complete Wiring Table

#FromToWirePurpose
1RC522 SDA(SS)GPIO8 (CE0)BLUEChip select
2RC522 MOSIGPIO10PURPLESPI data out
3RC522 MISOGPIO9YELLOWSPI data in
4RC522 SCKGPIO11BLUESPI clock
5RC522 RSTGPIO25GREENReset pin
6RC522 3.3VPi 3.3V (Pin 1)ORANGEPower (3.3V ONLY!)
7RC522 GNDPi GNDBLACKGround
8LDR SignalGPIO17YELLOWLight level reading
9LDR VCC / GND5V / GNDORANGE / BLACKPower sensor
10DHT11 DataGPIO4GREENTemperature reading
11DHT11 VCC / GND5V / GNDORANGE / BLACKPower sensor
12Servo SignalGPIO18BLUEDoor lock rotation
13Servo VCC / GND5V / GNDORANGE / BLACKPower servo
14Relay CH1 (Light) INGPIO22REDLight on/off control
15Relay CH2 (Fan) INGPIO23ORANGEFan on/off control
16Relay VCC / GND5V / GNDORANGE / BLACKPower relay module
17Buzzer SignalGPIO27BLUEAccess denied beep
18Buzzer VCC / GND5V / GNDORANGE / BLACKPower buzzer
💡

RC522 needs 3.3V, NOT 5V! The RFID reader module will get damaged if connected to the Pi's 5V pin. Always double-check you're using the 3.3V pin (physical pin 1) for the RC522's power.


Phase 03

Setting Up the Software

1

Flash Raspberry Pi OS onto the microSD card

Use the official Raspberry Pi Imager tool (from raspberrypi.com/software) on your computer to write Raspberry Pi OS onto the microSD card, then insert it into the Pi.

2

Enable SPI interface

Open a terminal on the Pi and run sudo raspi-config → Interface Options → SPI → Enable. This is required for the RFID reader to work. Reboot after enabling.

3

Install required Python libraries

Run these commands in the terminal:

Terminal — Install Libraries
sudo pip3 install mfrc522 RPi.GPIO Adafruit_DHT spidev
4

Create a folder for your project

Run mkdir smart_home && cd smart_home to keep your code organized.

5

Register your RFID card's unique ID

Run a simple test script (from the mfrc522 library examples) that prints the card's ID number when scanned. Note down this number — you'll add it to the "approved cards" list in our main code!


Phase 04

The Python Code

📦

Save this as smart_home.py inside your project folder, then run it with sudo python3 smart_home.py (sudo is needed for GPIO access).

Python — Smart Home Controller
# =============================================================
# SMART HOME -- RFID Door Lock + Auto Light + Auto Fan
#    MakeMindz | Kids Raspberry Pi Robotics Project
#    RFID unlocks the door, LDR controls the light,
#    and a temperature sensor controls the fan automatically!
# =============================================================

import RPi.GPIO as GPIO
import time
from mfrc522 import SimpleMFRC522
import Adafruit_DHT

# -- PIN DEFINITIONS --
LDR_PIN    = 17
RELAY_LIGHT= 22
RELAY_FAN  = 23
SERVO_PIN = 18
BUZZER_PIN= 27
DHT_PIN   = 4
DHT_SENSOR= Adafruit_DHT.DHT11

# -- APPROVED CARD IDS --
# Replace these with YOUR card's ID (printed when you scan it)
APPROVED_CARDS = [123456789012, 987654321098]

# -- SETTINGS --
TEMP_THRESHOLD = 30   # degrees C - fan turns ON above this
DOOR_OPEN_ANGLE = 90
DOOR_CLOSED_ANGLE = 0

# -- SETUP --
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BCM)
GPIO.setup(LDR_PIN, GPIO.IN)
GPIO.setup(RELAY_LIGHT, GPIO.OUT)
GPIO.setup(RELAY_FAN, GPIO.OUT)
GPIO.setup(BUZZER_PIN, GPIO.OUT)
GPIO.setup(SERVO_PIN, GPIO.OUT)

servo = GPIO.PWM(SERVO_PIN, 50)  # 50Hz for servo
servo.start(0)

reader = SimpleMFRC522()

def set_servo_angle(angle):
    # Move servo to a given angle (0-180)
    duty = 2 + (angle / 18)
    GPIO.output(SERVO_PIN, True)
    servo.ChangeDutyCycle(duty)
    time.sleep(0.5)
    GPIO.output(SERVO_PIN, False)
    servo.ChangeDutyCycle(0)

def unlock_door():
    print("Access granted! Door unlocking...")
    set_servo_angle(DOOR_OPEN_ANGLE)
    time.sleep(4)  # Stay open for 4 seconds
    set_servo_angle(DOOR_CLOSED_ANGLE)
    print("Door locked again.")

def deny_access():
    print("Access denied! Unknown card.")
    for _ in range(3):
        GPIO.output(BUZZER_PIN, GPIO.HIGH)
        time.sleep(0.2)
        GPIO.output(BUZZER_PIN, GPIO.LOW)
        time.sleep(0.1)

def check_light():
    # LDR reads HIGH in darkness, LOW in bright light (digital module)
    dark = GPIO.input(LDR_PIN)
    if dark:
        GPIO.output(RELAY_LIGHT, GPIO.HIGH)
        print("It's dark - Light turned ON")
    else:
        GPIO.output(RELAY_LIGHT, GPIO.LOW)
        print("It's bright - Light turned OFF")

def check_temperature():
    humidity, temp = Adafruit_DHT.read_retry(DHT_SENSOR, DHT_PIN)
    if temp is not None:
        print(f"Temperature: {temp:.1f} C")
        if temp > TEMP_THRESHOLD:
            GPIO.output(RELAY_FAN, GPIO.HIGH)
            print("Too warm - Fan turned ON")
        else:
            GPIO.output(RELAY_FAN, GPIO.LOW)
            print("Cool enough - Fan turned OFF")

# =============================================================
#  MAIN LOOP
# =============================================================
print("Smart Home Starting...")
print("Ready! Tap your RFID card at the door.")

try:
    while True:
        # -- Step 1: Check RFID for door access --
        print("Scanning for card...")
        card_id, text = reader.read()

        if card_id in APPROVED_CARDS:
            unlock_door()
        else:
            deny_access()

        # -- Step 2: Check light sensor --
        check_light()

        # -- Step 3: Check temperature sensor --
        check_temperature()

        time.sleep(1)

except KeyboardInterrupt:
    print("Smart Home shutting down safely...")
finally:
    servo.stop()
    GPIO.cleanup()

Brain Breakdown

How the Code Works — Step by Step

1

Reading the RFID Card

reader.read() waits until a card is tapped, then returns its unique ID number. We compare this ID against our APPROVED_CARDS list — just like a bouncer checking names on a guest list!

2

Controlling the Servo Lock

set_servo_angle() converts an angle (0-180°) into a PWM duty cycle the servo understands. unlock_door() swings it open, waits 4 seconds, then swings it shut again automatically.

3

Sensing Light with the LDR

check_light() reads the LDR module's digital output. Most LDR modules output HIGH when it's dark — so the code turns the light relay ON when darkness is detected, and OFF when it's bright.

4

Sensing Heat with DHT11

check_temperature() reads the current room temperature. If it's hotter than TEMP_THRESHOLD (30°C by default), the fan relay turns ON automatically.

5

The Main Loop — Keeping Watch Forever

The while True loop keeps checking the RFID reader, light sensor, and temperature sensor over and over, every second — making the home truly "smart" and always alert!

Terminal Output Example

Smart Home Starting...
Ready! Tap your RFID card at the door.
-----------------------------------------
Scanning for card...
Access granted! Door unlocking...
Door locked again.
It's dark - Light turned ON
Temperature: 31.0 C
Too warm - Fan turned ON
-----------------------------------------
Scanning for card...
Access denied! Unknown card.

Go Time!

Testing It Out 🧪

✅ Pre-Test Checklist

☑️ SPI enabled in raspi-config
☑️ Libraries installed
☑️ Card IDs added to code
☑️ All wires double-checked
☑️ Servo moves freely
☑️ Terminal ready to view output
1

Run the script

Type sudo python3 smart_home.py and press Enter. You should see "Smart Home Starting..." appear.

2

Tap your registered card

Hold your RFID card near the RC522 reader. The door servo should swing open, terminal shows "Access granted!", and it closes again after 4 seconds.

3

Tap an unregistered card (or your hand)

The door should stay locked, the buzzer beeps 3 times, and terminal shows "Access denied!"

4

Cover the LDR sensor with your hand

Simulating darkness — the light relay should click ON. Uncover it, and the light should turn back OFF.

5

Warm up the DHT11 sensor

Cup your hands around it or breathe on it gently. Once it crosses 30°C, the fan relay should click ON automatically!

All Systems Working
Door responds to cards, light reacts to darkness, fan reacts to heat.

Fix It

Troubleshooting Guide 🔧

❓ RFID reader not detected / "no module" error

Make sure SPI is enabled (sudo raspi-config) and you've rebooted afterward. Double-check SDA, MOSI, MISO, SCK, and RST pins match the wiring table exactly.

❓ Servo doesn't move or jitters constantly

Servos draw a lot of current — power it from a separate 5V supply if the Pi resets unexpectedly. Check the signal wire is on GPIO18 and GND is shared with the Pi.

❓ Light/fan relay clicks but doesn't power the bulb/fan

Check the relay's COM and NO terminals are correctly wired to your bulb/fan's power circuit. The Pi only controls the relay's switch — actual power for the bulb/fan comes from its own 5V source.

❓ DHT11 gives "sensor failure" errors

DHT11 sensors can be finicky — try reading 2-3 times in a row (the code already uses read_retry which retries automatically). Check the data pin isn't loose.

❓ "Permission denied" when running the script

GPIO access on Raspberry Pi needs administrator rights. Always run with sudo python3 smart_home.py, not just python3 smart_home.py.

❓ Light or fan stays ON all the time

Check your relay module's logic — some relay boards are "active LOW" (turn ON when signal is LOW, not HIGH). If yours behaves backwards, simply swap GPIO.HIGH and GPIO.LOW in the check_light() and check_temperature() functions.


Level Up!

Make It Even Smarter! 🚀

📱
Phone Notifications
Send a message to your phone via Telegram bot whenever someone unlocks the door!
📺
Add an OLED Display
Show "Welcome Home!" with the visitor's name and current temperature on a small screen.
📷
Door Camera
Add a Pi Camera module to snap a photo every time someone taps a card at the door.
🗣️
Voice Greeting
Use a speaker and text-to-speech to say "Welcome home!" out loud when the door unlocks.
📊
Access Log
Save every door-unlock event with date and time to a file, building a simple security log.
🌐
Web Dashboard
Build a simple Flask web page to view live temperature, light status, and door history from any browser.

Q & A

Frequently Asked Questions ❓

💬Is this safe to use as a real house door lock?
This project is designed as an educational model using small low-power components. Real home security systems need professional-grade hardware, backup power, and proper installation. Treat this as a fantastic learning model, not a replacement for a real door lock!
💬Can I add more than 2 approved RFID cards?
Absolutely! Just add more ID numbers to the APPROVED_CARDS list in the code, separated by commas. You could have one for every family member!
💬Why does the LDR need a digital module instead of just a resistor?
A raw LDR gives an analog (continuously changing) signal, but Raspberry Pi's GPIO pins can only read digital HIGH/LOW signals directly. The LDR module includes a small comparator circuit that converts the analog brightness level into a simple digital signal Raspberry Pi can understand.
💬What's the difference between Raspberry Pi and Arduino for this project?
Raspberry Pi runs a full operating system and Python, making it great for projects needing multiple sensors, networking, or future AI/camera upgrades. Arduino is simpler and great for direct hardware control, but Raspberry Pi's extra power suits a multi-feature smart home nicely.
💬Can younger kids build this project?
This is an intermediate-to-advanced project due to the Python coding and multiple sensor types involved. Kids aged 12+ can handle it well with adult guidance on the software setup steps. The house-building and testing phases are great for younger siblings to help with too!
💬What happens if the power goes out?
Like most smart home systems, this project needs continuous power to function. If power is lost, the door would stay in whatever position it was last in. This is a great discussion point about why real smart homes often include battery backups!
#SmartHome #RaspberryPi #RFIDLock #HomeAutomation #KidsMaker #MakeMindz #STEM #PythonProject #IoT #AutoLight #AutoFan #ScienceFair
🏠

Made with ❤️ by MakeMindz — Teaching Electronics, One Project at a Time!

Share your build with #MakeMindz and inspire other young makers!

Comments

Product Cards
Buddy Bot eBook
⭐ New 2026 Release
Build Your
Own Robot!
3D design, wiring &
Arduino coding.
Young inventors love it!
🖨️
3D Print
All parts
Wire it
Circuit guide
💻
Code it
Arduino IDE
🤖
Watch it
Walk & react
📋 Your Details
Enter your name
Valid 10-digit no.
Enter a valid email
Special Website Offer
₹499 300
🌍 International: $5 USD
One-time · Instant digital delivery
🔒 Secured by Razorpay · Your data is safe
📄 Download Free Sample Copy
🔒 Secured by Razorpay · Your data is safe
🍓
Raspberry Pi Pico Mastery
21 Projects
⚡ Launch Price — 80% OFF
Learn Pico
Build 21 Projects!
MicroPython · Wokwi
IoT · Certificate
Perfect for beginners!
🖥️
Wokwi
No hardware
🐍
MicroPy
From zero
🔨
21 Projects
IoT + sensors
📄
Certificate
Verified cert
📋 Your Details
Enter your name
Valid 10-digit no.
Enter a valid email
Special Launch Offer
₹999 200 80% OFF
🌍 International: $5 USD
One-time · Lifetime access · No subscription
🔒 Secured by Razorpay · UPI · Cards · NetBanking
🎉

You're in!

Payment successful! Your Buddy Bot eBook is ready. Time to build!

📖 Access Your eBook Now
🎉

Enrolled!

Payment successful! Lifetime access to all 21 Pico Projects is yours!

🍓 Go to My Course