Door bell with pi camera and motion detection

Ive managed to put together a doorbell system which takes video footage when the motion detector is tripped and takes a few stills when the doorbell is pressed.
The motion sensor and doorbel is connected to the GPIO pins on a Pi.
It isnt in use yet but its been active on my desk now for a week and havent had a glitch yet.

Still fairly basic there is no video or audio communication implemented yet although that will be something I will want to add in the near future.
Also I still need to find a way of getting it to communicate with home assistant, still not sure how I am going to achieve that.
Im still new to Raspberry pi, Linux and Python, so Im learning as I go.
Let me know what you think, any suggestions would be appreciated.
Just need a momentary push button, Motion sensor,HC-SR501, raspberry pi, speaker, Pi Camera, WIFI Dongle.
Once I figure how to post the code I will

4 Likes

OK wont let me upload the file not quite sure how to share this

Paste your code into the forum editor. Then select the code block and press the pre-formatted text button as indicated below:

Also, screen shots would be great as I am sure others like me will want to see what the notification messages look like.

1 Like

Thought about doing something similar, but to avoid trailing wires was considering using an amazon dash button for the doorbell.

A useful guide to dash is on http://www.bruhautomation.com/single-post/2016/11/22/How-To-Use-an-Amazon-Dash-with-IFTTT-and-Home-Assistant

Also useful Capture Amazon Dash button press

2 Likes
import RPi.GPIO as GPIO
import time
import datetime
import subprocess
import paho.mqtt.client as mqtt
import paho.mqtt.publish as publish
from picamera import PiCamera
from subprocess import call
import shutil
# Smart doorbell script adapted by Lee Goodman (Meganoodle from example online
# https://www.modmypi.com/blog/raspberry-pi-gpio-sensing-motion-detection
#
# COMPONENTS
#
# Raspberry Pi 2 (Will use Pi zero when it arrives)
# Raspberry Pi Camera V2
# Motion sensor...HC-SR501 
# Door bell button..Momentary (normally open)
# Wifi Dongle
#
# SOFTWARE
# Latest version of Raspian 
#
# Camera and GPIO must be enabled in raspi-config
#
# Pinouts
# Motion sensor -------Raspberry Pi
#   VCC----------------5V
#   GND----------------GND
#   DATA---------------GPIO 7 (PIN 26)
#=======================================
# Door Bell Button-----Raspberry Pi
# Feed-----------------GND
# Load-----------------GPIO 23 (PIN 16)
#=======================================
#

# Setup camera object
camera = PiCamera()
camera.hflip = False
# Flip camera (mounted upside down).
camera.vflip = True
GPIO.setmode(GPIO.BCM)

# GPIO 7 for the motion sensor (pin26)
PIR_PIN = 7
# GPIO 23 for doorbell switch (pin 16)
DB_PIN = 23

# Motion sensor pin setup
GPIO.setup(PIR_PIN, GPIO.IN)

# Doorbell Button setup as pullup
GPIO.setup(DB_PIN, GPIO.IN, pull_up_down=GPIO.PUD_UP)
ImagePath='/home/pi/doorbell/camera/'
OldTime=time.time
TInterval=20
ainterval=0
# Take 3 snapsots ( file name is the date and time .jpg

def SNAPSHOT(Pressed):
    print 'Snapping...'
    Tstamp = ImagePath+datetime.datetime.now().strftime('%b-%d-%I%M%S%p-%G')+'.jpg'
    camera.capture ('/home/pi/doorbell/camera/frequent.jpg')
    if Pressed<>1:
        shutil.copy('/home/pi/doorbell/camera/frequent.jpg',Tstamp)        
        print 'Snapshot Saved to "'+Tstamp+'"'
    print'Snapshot complete'   
# Record footage, filename is the date and time .h265     
def FOOTAGESTART():
    print 'Recording Footage...'
    Tstamp = '/home/pi/doorbell/camera/'+datetime.datetime.now().strftime('%b-%d-%I%M%S%p-%G')
    Tstamp = Tstamp+'.h264'
    camera.start_recording(Tstamp)
    
def FOOTAGESTOP():
    camera.stop_recording()
    print 'Recording Footage Stopped...'
    
# Motion triggered function
# Add commands for when motion sensor is triggered
def MOTION(PIR_PIN):
    if GPIO.input(PIR_PIN)==1:
        print "Motion Detected!"
        localtime = time.asctime( time.localtime(time.time()) )
        PIRState="DBMT"
        print "Local current time :", localtime
        # Play a short beep when motion detected (Using commandline player until I figure how to use code).
        subprocess.call('aplay bip2.wav',shell=True)
        FOOTAGESTART()
        SNAPSHOT(0)
    else:
        FOOTAGESTOP()
        PIRState="DBMR"
        print"PIR Ready..."
    publish.single("doorpi/motion", PIRState, hostname="192.168.0.8") 
    
# Doorbell pressed function
# Add commands for when the doorbell is pressed
def DOORBELLON(DB_PIN):      
    if GPIO.input(DB_PIN)<>1:
        DBState='DBBP'
        publish.single("doorpi/button", DBState, hostname="192.168.0.8")
        print "Doorbell Pressed..."
        localtime = time.asctime( time.localtime(time.time()) )
        print "Local current time :", localtime
        # Play doorbell tone via commandline
        subprocess.call('aplay /home/pi/doorbell/doorbell-6.wav', shell=True)
        SNAPSHOT(0)
        
    if GPIO.input(DB_PIN)<>0:
        DBState="DBBR"
        publish.single("doorpi/button", DBState, hostname="192.168.0.8")
        print "Doorbell Released..."
        
        
# Startup message
print "Smart Doorbell ... (CTRL+C to exit)"
DBState="DBBR"
PIRState="DBMR"
#publish.username_pw_set(username="pi",password="raspberry")
publish.single("doorpi/button", DBState, hostname="192.168.0.8")
publish.single("doorpi/motion", PIRState, hostname="192.168.0.8")
time.sleep(2)
print "Ready..."


# Handle interupts
# Bounce time set to 4 seconds to avoid the doorbell tone repeating constantly.
try:
    GPIO.add_event_detect(DB_PIN,GPIO.BOTH, callback=DOORBELLON, bouncetime=4000 )
    GPIO.add_event_detect(PIR_PIN, GPIO.BOTH, callback=MOTION)   
        
    while 1:
        ainterval=ainterval+1
        if ainterval > TInterval:
            if GPIO.input(DB_PIN)==1:
                if GPIO.input(PIR_PIN)==0:
                    SNAPSHOT(1)
                    ainterval=0
        time.sleep(1)
        
# Cleanup on exit
except KeyboardInterrupt:
    print " Quit"
    GPIO.cleanup()
1 Like
  - platform: mqtt
    state_topic: 'doorpi/button'
    name: 'Doorbell Button'
    payload_on: "DBBP"
    payload_off: "DBBR"
    qos: 0

  - platform: mqtt
    state_topic: 'doorpi/motion'
    name: 'Doorbell Motion'
    payload_on: "DBMT"
    payload_off: "DBMR"
    qos: 0
camera:
  - platform: generic
    name: DoorBell
    still_image_url: http://192.168.0.30:8000/frequent.jpg
1 Like

Got it thanks.

Addidtionally in order for the camera to work with HA you need a directory setup named camera should be a child directory from where the python code is.
I havent got around to programming it to create the directories yet.
as a short term workaround I Change directory into the camera dir and run the simple http.

python -m SimpleHTTPServer

These bits are just a workaround until I learn and add new bits to it.
U need to find a couple of wav files one for the door bell and the other is for motion detection.
I used a dingdong sound for the doorbell and a discreet short blip for the motion.
Alter the names of the files from the code.

doorbell
subprocess.call(‘aplay /home/pi/doorbell/doorbell-6.wav’, shell=True)

Motion
subprocess.call(‘aplay bip2.wav’,shell=True)

As I said before, I am open to any suggestions.

Its still a work in progress, ( just sitting on my desk running). But I am now at the stage where I am comfortable putting it all in a box and mount it at the front door.

Only thing with dash is there is a lot of latency, I tried that sometimes it was ok , but mainly it was really slow, up to 30 seconds.
I used IFTTT following the video from BRUH.

1 Like

RE the trailing wires, I am with you on that, I intend to run this on a pi zero and power it with a battery (once I figured out how).
but then the sound would need to come from the HA PI which can easily setup with some scripts and automations.

Screen shots of my frontend with the sensors and the camera

Sure, no need to use IFTTT however. Could try MQTT or rest.
The latency comes from the the dash connecting to the wifi, so in my experience it was literally a couple of seconds before the push was registered on my home network.

Another idea I will throw out there would be to use the facial recognition to detect when someone is at the door, no button required at all then :grinning:

1 Like

Also nodeMCU is worth a look. Pi nano requires separate dongle for wifi, and has a larger footprint than nodeMCU.

1 Like

Yeah I want to play with this, but once I got it on my door to properly test it, then I need to do more research.

1 Like

Indeed, probably lower pwer consumption too.
I am only just getting used to the Pi and Jasper, although I have toyed with arduino sketches, most of my sensors are on the arduino nano using the mysensors platform.

I wouldnt even know if the NodeMCU is cabable of processing images from a camera , let alone knowing how to do it.
I might have a little search to see if its easy enough to do. But now ive started on the pi I still want to finish it, my todo list is still fairly long.

1-Build a http frontend to change options and settings, and maybe a live feed, to view remotely.
2-Workout how to power it outside,(battery power is preferable)
3-Cleanup some of the code (use embedded rather than shell to command prompt)
4-Add intercom system (talk to the visitor via android or os app)
5-Facial Recognition, (have it greet you as you approach the door)
6-User presets on HA (this depends on the facial recognition) so if I walk in the door the pc will switch on , my music palylist will start playing, etc.
7-Wrap it all up in a neat box, so it looks good on the wall.

These items are still pie in the sky , I am still not sure how possible it will be, I will keep you posted.

1 Like

Awesome, looking forward to hearning how you get on. This project might interest you too https://www.hackster.io/windows-iot/windows-iot-facial-recognition-door-e087ce

Some interesting devices available if you are feeling adventurous later down the line https://raymondtunning.wordpress.com/2016/09/13/more-about-the-a20-plus-pictures-of-the-final-product/

1 Like

Hi,

I still did not had installed HA and bough the described (here below) board but here is my quest :wink:

I did not read all the above comments but I also want what you talked about in those conditions (priority order) :

  1. be able to catch on motion detection (just at front of the door but also at 6 meter to survey my car : if someone is walking around it with bad intentions)
  2. then it does not need a reaction when the doorbell button is pressed due to the catch got on motion detection
  3. OpenCV face recognition (with python) : relevant and non-relevant detected people
  4. in place of buying a RPi + Camera I though to use an already integrated board the Banana Pi D1
  5. latency problem

Solution found (corresponding to the above points) :

  1. and 3)
    a) no need of sensor due to the fact the motion program do it itself - or OpenCV is also able to do it
    b) I just got the idea to also be able to use OpenCV to distinguish relevant from non relevant detections - I means distinguish known family people (then know when they are present at home) from friends, from people recurrently coming to my door (listen, knocking, …), from undesirable peoples and just one time visitors

  2. to avoid latency problem I tough to use a local installation of a IFTTT like well know as Trigger Happy. But it still need to be tested by community.

Sincerely thanks for your feedbacks.

1 Like

Yes I am intrigued. although I must avoid the temptation of jumping ship, (This is why my shed is a mess, too many unfinished projects lol).

Look what just landed in my inbox, looks like just the thing!

And in action

3 Likes

That might be useful. Even if I dont mount it to the the window it would certainly make it easier to mount inside a box.