pip install RPi.GPIO
import RPi.GPIO as GPIO
import time
import smtplib
from email.mime.text import MIMEText
# GPIO pin setup
PIR_PIN = 17
DOOR_PIN = 18
MOTION_LED_PIN = 19
DOOR_LED_PIN = 20
BUZZER_PIN = 21
# Email configuration
EMAIL_FROM = "[email protected]"
EMAIL_TO = "[email protected]"
EMAIL_SUBJECT = "Motion Detected"
EMAIL_BODY = "Motion has been detected."
SMTP_SERVER = 'smtp.gmail.com'
SMTP_PORT = 587
SMTP_USERNAME = "[email protected]"
SMTP_PASSWORD = "@hmedesh@l635"
# GPIO setup
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BCM)
GPIO.setup(PIR_PIN, GPIO.IN)
GPIO.setup(DOOR_PIN, GPIO.IN)
GPIO.setup(MOTION_LED_PIN, GPIO.OUT)
GPIO.setup(DOOR_LED_PIN, GPIO.OUT)
GPIO.setup(BUZZER_PIN, GPIO.OUT)
# Function to send email
def send_email(subject, body):
msg = MIMEText(body)
msg['[email protected]'] = EMAIL_FROM
msg['[email protected]'] = EMAIL_TO
msg['motion detected'] = subject
server = smtplib.SMTP(SMTP_SERVER, SMTP_PORT)
server.starttls()
server.login(SMTP_USERNAME, SMTP_PASSWORD)
server.sendmail(EMAIL_FROM, EMAIL_TO, msg.as_string())
server.quit()
# Function to handle motion detection
def motion_detected():
print("Motion detected!")
GPIO.output(MOTION_LED_PIN, GPIO.HIGH) # Turn on motion LED
GPIO.output(BUZZER_PIN, GPIO.HIGH) # Turn on buzzer
send_email(EMAIL_SUBJECT, EMAIL_BODY) # Send email
# Function to handle door opening
def door_opened():
print("Door opened!")
GPIO.output(DOOR_LED_PIN, GPIO.HIGH) # Turn on door LED
GPIO.output(BUZZER_PIN, GPIO.HIGH) # Turn on buzzer
send_email(EMAIL_SUBJECT, "Door has been opened.")
# Function to handle door closing
def door_closed():
print("Door closed!")
GPIO.output(DOOR_LED_PIN, GPIO.LOW) # Turn off door LED
GPIO.output(BUZZER_PIN, GPIO.LOW) # Turn off buzzer
send_email(EMAIL_SUBJECT, "Door has been closed.")
try:
while True:
if GPIO.input(PIR_PIN):
motion_detected()
while GPIO.input(PIR_PIN): # Wait until motion stops
time.sleep(0.1)
GPIO.output(MOTION_LED_PIN, GPIO.LOW) # Turn off motion LED
if GPIO.input(DOOR_PIN):
door_opened()
while GPIO.input(DOOR_PIN): # Wait until door closes
time.sleep(0.1)
door_closed()
GPIO.output(DOOR_LED_PIN, GPIO.LOW) # Turn off door LED
time.sleep(0.1) # Check sensors every 0.1 seconds
except KeyboardInterrupt:
GPIO.cleanup()