it is a bit clunky but up and running. I had an issue with starting and stopping recordings that didn't exist, so introduced a recording variable.
when motion is detected by GPIO rising the counter is set to 30 (regardless of any other state)
if the counter = more than 0 but recording is 0 it will set recording to 1 and start the recording
if the counter = more than 0 and recording = 1 every second 1 is subtracted from the counter
if the counter = 0 and recording = 1 the recording is stopped, video is increased by 1 (used for the file numbers) and recording is set to 0
if the counter = 0 and the recording = 0 it runs in idle
counter = 0
recording = 0
video = 1
import RPi.GPIO as GPIO
import time
import picamera
GPIO.setmode(GPIO.BCM)
PIR_PIN = 7
GPIO.setup(PIR_PIN, GPIO.IN)
camera = picamera.PiCamera()
camera.rotation = 180
print "trail camera v1.0\n"
time.sleep(1)
print "ready\n"
time.sleep(1)
def motion(PIR_PIN):
global counter
print "motion detected\n"
counter = 30
time.sleep(1)
GPIO.add_event_detect(PIR_PIN, GPIO.RISING, callback=motion)
while True:
if counter > 0:
if recording == 0:
recording = 1
print "recording\n"
camera.start_recording('/home/pi/Desktop/video%03d.h264' % video)
time.sleep(1)
if recording == 1:
print (counter)
print ""
time.sleep(1)
counter -= 1
if counter == 0:
if recording == 0:
print "idle\n"
time.sleep(5)
if recording == 1:
print "recording stopped\n"
camera.stop_recording()
video += 1
recording = 0
time.sleep(1)
try:
while 1:
time.sleep(100)
except KeyboardInterrupt:
print "Quit"
GPIO.cleanup()
the last thing to solve is putting the video in an MP4 container, I have installed MP4Box and can convert the videos in terminal, I just need to work out how to run this in the python script.
MP4Box -fps 30 -add myvid.h264 myvid.mp4