I want to record a video with a webcam when a PIR sensor detect motion, I have the picamera library installed, can any one help, thank you?

import RPi.GPIO as GPIO
import time
import picamera
import datetime  # new

def get_file_name():  # new
    return datetime.datetime.now().strftime("%Y-%m-%d_%H.%M.%S.h264")

sensor = 4

GPIO.setup(sensor, GPIO.IN, GPIO.PUD_DOWN)

previous_state = False

current_state = False

cam = picamera.PiCamera()

while True:


    previous_state = current_state
    current_state = GPIO.input(sensor)
    if current_state != previous_state:
        new_state = "HIGH" if current_state else "LOW"
        print("GPIO pin %s is %s" % (sensor, new_state))

        if current_state:
            fileName = get_file_name()  # new
            cam.start_recording(fileName)  # new
            cam.stop_recording()  # new
  • Another user and I have cleaned up the content but I can clearly see that the python code provided is incomplete - it is truncated just as it would be getting interested in that the last if current_state: line would be followed by a command to start recording as a result of the GPIO pin being taken high, presumably by the PIR output signal. If it was me writing code I want to do something to keep recording until a certain time after the GPIO pin goes low again - though that would depend on how the PIR device behaves (does it have its own "hold on" time after it ceases a detection?)
    – SlySven
    May 7, 2016 at 3:28
  • yes its incomplete i edit it now code with picamera
    – happy
    May 7, 2016 at 10:11
  • 1
    You mention you're using a webcam, but the picamera module only works with the Pi's camera module, not with USB webcams. Can you confirm what sort of camera you're using?
    – Dave Jones
    May 7, 2016 at 20:42
  • that program is with picamera but i wan to use a webcam and I don't know haw
    – happy
    May 8, 2016 at 22:30

1 Answer 1


If you don't need any custom logic, then you could install motion (sudo apt install motion), tweak its config file at /etc/motion/motion.conf, and have it record videos in your desired format (mp4, avi, swf, flv, etc..) when a 'motion event' occurs.

If you want movies to be saved to files, then make sure you set:

ffmpeg_output_movies on
ffmpeg_video_codec mp4  # can also use other formats
stream_localhost off  # otherwise only localhost connections are allowed
output_pictures off

It includes an HTTP MJPG streaming server which you can watch from your browser or hook to specialized webcam apps (see stream_port in the config).

You can run your own scripts or commands on certain event hooks. The useful ones are:

  • on_event_start — fires when motion is detected
  • on_movie_end — fires after a movie has been created, receives the path of the created video file, meaning you can e.g. automatically email it to yourself or send to a telegram chat.
  • on_camera_lost — a hook you can use to take action in case something fails, i.e. restart the motion service or reboot your rpi.

Getting it to work the way you want involves getting your config right, and googling will return enough results for different scenarios, e.g. like this one.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.