ogamiitto
Posts: 15
Joined: Fri Sep 09, 2016 3:10 pm

a little help for beginner with my code please

Tue Sep 13, 2016 5:11 pm

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
Starting along the road of Home Educating my 4 year old. So desperately attempting to learn some coding so that I can get her started. No doubt she'll be past me and running soon enough.

Ever thankful to the community for all help received!

User avatar
davef21370
Posts: 897
Joined: Fri Sep 21, 2012 4:13 pm
Location: Earth But Not Grounded

Re: a little help for beginner with my code please

Tue Sep 13, 2016 5:38 pm

Try camera.close() when you clean up at the end.

Dave.
Apple say... Monkey do !!

User avatar
bensimmo
Posts: 4182
Joined: Sun Dec 28, 2014 3:02 pm
Location: East Yorkshire

Re: a little help for beginner with my code please

Tue Sep 13, 2016 7:17 pm

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)

User avatar
bensimmo
Posts: 4182
Joined: Sun Dec 28, 2014 3:02 pm
Location: East Yorkshire

Re: a little help for beginner with my code please

Tue Sep 13, 2016 7:25 pm

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/

ogamiitto
Posts: 15
Joined: Fri Sep 09, 2016 3:10 pm

Re: a little help for beginner with my code please

Wed Sep 14, 2016 6:58 am

davef21370 wrote:Try camera.close() when you clean up at the end.

Dave.
Thank you, this made no difference to the error.
Starting along the road of Home Educating my 4 year old. So desperately attempting to learn some coding so that I can get her started. No doubt she'll be past me and running soon enough.

Ever thankful to the community for all help received!

ogamiitto
Posts: 15
Joined: Fri Sep 09, 2016 3:10 pm

Re: a little help for beginner with my code please

Wed Sep 14, 2016 7:03 am

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.
Starting along the road of Home Educating my 4 year old. So desperately attempting to learn some coding so that I can get her started. No doubt she'll be past me and running soon enough.

Ever thankful to the community for all help received!

ogamiitto
Posts: 15
Joined: Fri Sep 09, 2016 3:10 pm

Re: a little help for beginner with my code please

Wed Sep 14, 2016 8:58 am

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
Starting along the road of Home Educating my 4 year old. So desperately attempting to learn some coding so that I can get her started. No doubt she'll be past me and running soon enough.

Ever thankful to the community for all help received!

User avatar
bensimmo
Posts: 4182
Joined: Sun Dec 28, 2014 3:02 pm
Location: East Yorkshire

Re: a little help for beginner with my code please

Wed Sep 14, 2016 3:28 pm

I don't think you need the GPIO parts

ogamiitto
Posts: 15
Joined: Fri Sep 09, 2016 3:10 pm

Re: a little help for beginner with my code please

Thu Sep 15, 2016 4:07 pm

OK, I will try without thank you.
Starting along the road of Home Educating my 4 year old. So desperately attempting to learn some coding so that I can get her started. No doubt she'll be past me and running soon enough.

Ever thankful to the community for all help received!

typxxi
Posts: 44
Joined: Sat Mar 05, 2016 6:11 pm
Location: GERMANY

Re: a little help for beginner with my code please

Sun Nov 27, 2016 10:56 am

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
WOLF

typxxi
Posts: 44
Joined: Sat Mar 05, 2016 6:11 pm
Location: GERMANY

Re: a little help for beginner with my code please

Mon Nov 28, 2016 11:46 am

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
WOLF

vines55
Posts: 1
Joined: Sat Oct 21, 2017 5:03 pm

Re: a little help for beginner with my code please

Sat Oct 21, 2017 5:07 pm

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?

Return to “Python”