Page 1 of 1

a little help for beginner with my code please

Posted: Tue Sep 13, 2016 5:11 pm
by ogamiitto
Hi everyone

I must first say I am a complete beginner and so I apologise in advance if I'm missing the obvious.

I'm attempting to write code for a camera trap. I would like it to basically record video while motion is being detected and then to stop recording when there is nothing going on. So this is what I have so far:-

Code: Select all

#-*-coding utf-8-*-
import RPi.GPIO as GPIO
import time
from picamera import PiCamera
from time import sleep

camera = PiCamera()

GPIO.setmode(GPIO.BCM)
PIR_PIN = 7
GPIO.setup(PIR_PIN, GPIO.IN)
Current_State  = 0
Previous_State = 0

try:
    print "PIR Module Test (CTRL+C to exit)"
    time.sleep(2)
    print("Ready")
    
    while True:
       Current_State = GPIO.input(PIR_PIN)
       if Current_State==1 and Previous_State==0:
            print("Motion Detected")
            camera.rotation = 180
            camera.start_preview(alpha=200)
            for i in range(20):
                camera.start_recording('/home/pi/video{}.h264'.format(i))
                print('Captured pivid{}.264'.format(i))
                i += 1
                time.sleep(20)
            if Current_State==0 and Previous_State==1:
                camera.stop_recording()
                camera.stop_preview()
                time.sleep(1)
                print "  Ready"
    
except KeyboardInterrupt:
    print (" Quit")
GPIO.cleanup()

when i run the program it starts OK but then comes up with this error:-

pi@raspberrypi:~ $ sudo python pircamera.py
PIR Module Test (CTRL+C to exit)
Ready
Motion Detected
Captured pivid0.264
Traceback (most recent call last):
File "pircamera.py", line 27, in <module>
camera.start_recording('/home/pi/video{}.h264'.format(i))
File "/usr/lib/python2.7/dist-packages/picamera/camera.py", line 1012, in start_recording
camera_port, output_port = self._get_ports(True, splitter_port)
File "/usr/lib/python2.7/dist-packages/picamera/camera.py", line 545, in _get_ports
'The camera is already using port %d ' % splitter_port)
picamera.exc.PiCameraAlreadyRecording: The camera is already using port 1
sys.excepthook is missing
lost sys.stderr
pi@raspberrypi:~ $

I'm guessing it's trying to start the camera again once it's already recording but I'm not sure how to stop it.

Any help gratefully received.
ogami

Re: a little help for beginner with my code please

Posted: Tue Sep 13, 2016 5:38 pm
by davef21370
Try camera.close() when you clean up at the end.

Dave.

Re: a little help for beginner with my code please

Posted: Tue Sep 13, 2016 7:17 pm
by bensimmo

Code: Select all

            for i in range(20):
                camera.start_recording('/home/pi/video{}.h264'.format(i))
                print('Captured pivid{}.264'.format(i))
                i += 1
                time.sleep(20)
Is it this loop trying to loop through while still recording.
What are you looping for ?

(python beginner myself, so learning from all of this also)

Re: a little help for beginner with my code please

Posted: Tue Sep 13, 2016 7:25 pm
by bensimmo
also not use camera.wait_recording https://picamera.readthedocs.io/en/rele ... -to-a-file

Other can comment on the way you are triggering and breaking the loop.

While I think about it, a quick look and the "built in-ish" gpiozero module has PIR so have a look at http://gpiozero.readthedocs.io/en/v1.3. ... -d-sun-pir



EDIT to add now i've had a look...

Missing the obvious is here... but look only if you want the solution now I've had a look at it.
https://www.raspberrypi.org/learning/parent-detector/

Re: a little help for beginner with my code please

Posted: Wed Sep 14, 2016 6:58 am
by ogamiitto
davef21370 wrote:Try camera.close() when you clean up at the end.

Dave.
Thank you, this made no difference to the error.

Re: a little help for beginner with my code please

Posted: Wed Sep 14, 2016 7:03 am
by ogamiitto
Thank you bensimmo, very helpful links. I have indeed just jumped in to the parent detector page and am now rewriting my code. I had been round a few places on the web but had not seen that one.

I think I was definitely trying to over complicate things so I'm doing a complete start over. However I have learned some things so its not all a loss. Hopefully we can get this project off the ground very soon. (watch as we make a completely un-waterproof box and get the whole thing fried;) I'll post my update soon.

Re: a little help for beginner with my code please

Posted: Wed Sep 14, 2016 8:58 am
by ogamiitto
code now working as i want completely redone. thank you for all your help!!

Code: Select all

import RPi.GPIO as GPIO
from gpiozero import MotionSensor
from picamera import PiCamera
from datetime import datetime
import time

pir = MotionSensor(7)
camera = PiCamera()


try:
    print ("PIR Module Test (CTRL+C to exit)")
    time.sleep(2)
    print("Ready")
    
    while True:
        pir.wait_for_motion()
        print ("Motion Detected!")
        filename = datetime.now().strftime("%Y-%m-%d_%H.%M.%S.h264")
        camera.rotation = 180
        camera.start_preview(alpha=200)
        camera.start_recording(filename)
        pir.wait_for_no_motion()
        camera.stop_recording()
        camera.stop_preview()
        print ("Motion Stopped!")
    
except KeyboardInterrupt:
    print (" Quit")
GPIO.cleanup(7)
camera.close
i`ll take the camera preview parts out to actually run it

thank you once again

Re: a little help for beginner with my code please

Posted: Wed Sep 14, 2016 3:28 pm
by bensimmo
I don't think you need the GPIO parts

Re: a little help for beginner with my code please

Posted: Thu Sep 15, 2016 4:07 pm
by ogamiitto
OK, I will try without thank you.

Re: a little help for beginner with my code please

Posted: Sun Nov 27, 2016 10:56 am
by typxxi
Hey Ogamiitto,

your code works but I ran into problems, cause "CTRL+C" does not work.

Therefore I can not stop the code and if I close the terminal window I will get problems with the next start cause ... "failed to enable port" (sorry , can not copy the full errormessage cause my pi zero is not network connected)

Can you check that?

THanks a lot for sharing your result....

Wolf

Re: a little help for beginner with my code please

Posted: Mon Nov 28, 2016 11:46 am
by typxxi
Hey Ogamiitto,

regarding "CTRL + C" does not work and the following bug after restarting the script I have found that "workaround":

If you press "CTRL + 4" you will quit that script
+
you will be able to restart the script without that error I mentioned before.

So far: this is the best PIR detected Pi CAM recording I found.


Here is just a usefull add on which will show a textmessage regarding which CAM recorded that file and a date - time stamp. Insert the following lines after:camera.start_recording(filename)

Code: Select all

camera.start_recording(filename)

CAM = "FRONT 1"
SECONDS = 8
start = datetime.now()
while (datetime.now() - start).seconds < SECONDS:
  camera.annotate_text = "CAMERA " + CAM + ": " + datetime.now().strftime('%d.%m.%Y  -  %H:%M:%S')
  camera.wait_recording(0.2)
CAM is the name of the camera which will be displayed and SECONDS is the duration of each videoclip after a motion has been detected.

I also added a conversion into a MP4 file and a move to NAS for better access. Meanwhile at least under Windows VLC supports h264 file format for example by drag and drop.

Enjoy Pi + Cam

Wolf

Re: a little help for beginner with my code please

Posted: Sat Oct 21, 2017 5:07 pm
by vines55
New to this, as well. I am working to program parent detector and want to use a Sync-it light rather than a camera. Does anyone know the specifics on the coding around using the light versus a camera?