Setting up Wireless motion-detect cam

This project is based on a post by dozencrows here which explored the use of a Raspberry Pi camera board as a motion detecting video cam. It is based on the motion package in Debian. He has recompiled this with a slightly different configuration, making it convenient to work with the Raspberry Pi cam board. I take no credit for the code, but hope that details of how I have se it up on my system, and how I have connected it to a Synology NAS with built in Surveillance Station will be of interest to others. The original thread has multiple posts on it, and it can be confusing to get to grips with the code as a result.

What you need:

A Raspberry Pi, with PSU, camera board and WiFi adaptor (It would work with an ethernet connection, but it makes it less convenient for placing the camera is a suitable location. An SD card containing an uptodate copy of the wheezy-raspian distribution. If you have a blank card you can put the distribution on it together with configuring the wifi dongle by following the first section of my article here. You should also remember to check that the camera code support is enabled by typing  sudo raspi-config and setting option 5
For convenience I have ssh enabled on my card so that I can carry out the work on it via a link to a terminal on my main computer.

My wireless lan port has ip address 192.168.1.98, so I connect to the pi using
ssh pi@192.168.1.98 from a terminal window on my mac (you can install and use  putty on Windows)

Now to get going:

First make sure (if you haven’t already) that your raspian is up to date.
type
sudo apt-get update
sudo apt-get upgrade
it is also a good idea to make sure your firmware is up to date

sudo apt-get install rpi-update
and run it sudo rpi-update
a reboot is required when this is finished
sudo shutdown -r now
(you will have to reconnect via ssh when the Rpi has restarted if you are using a remote terminal)

Now install the motion program
sudo apt-get install motion

We don’t actually use this version, but it does insure that all the necessary dependencies are installed as well

sudo apt-get install libjpeg62

create and enter a directory called mmal in the user pi home directory using
cd ~/
mkdir mmal
cd mmal
download dozencrow’s version of the motion program using
wget https://www.dropbox.com/s/xdfcxm5hu71s97d/motion-mmal.tar.gz
and extract the contents with
tar -zxvf motion-mmal.tar.gz
you now modify the configuration file, by opening it with the editor nano
nano motion-mmalcam.conf
nano hints
To insert a blank line, move to the beginning of a line and press return
To delete a line position the cursor on the line and press ctrl+k
use the backspace arrow to delete characters
you can search for a string by typing ctrl+w and inserting the string you wish to find.
When you have finished amending the file use ctrl+o to write out the amended file, selecting the existing filename to overwrite by pressing return. Then select ctrl+x to exit the editor.

you are going to alter the lines for 
width
height
target_dir
output_pictures
text _left
logfile
search for them in turn using ctrl+w and set them as follows

width 640
height 480
target_dir /home/pi/m-video
output_pictures off
text_left Pi-cam %t
logfile  /home/pi/mmal/motion.log

then write the changes out using ctrl+o push return and exit the editor with ctrl+x

So that there is no confusion as to which motion binary is running I rename the one in the mmal directory using mv motion motion-mmal

Assuming your camera board is correctly installed, you are now in a position to test it out
In your terminal window, from the mmal directory type
./motion-mmal -n -c motion-mmalcam.conf
where upon the camera board red led should light, and if you start a browser on another computer on your local network (Internet Explorer doesn’t work but Chrome, Firefox and Safari are ok) you should see live pictures at http://192.168.1.98:8081
You quit the process by typing ctrl+c

The start stop process is hardly ideal, so I have written a couple of scripts to start and stop the process.

type nano startmotion
In the editor window type
#!/bin/sh
nohup ~/mmal/motion-mmal -n -c motion-mmalcam.conf 1>/dev/null 2>&1 </dev/null &

type ctrl+o then push the return key to write the text, followed by ctrl+x to exit the editor
chmod 755 startmotion to make it executable

type nano stopmotion
In the editor window type

#!/bin/sh
ps -ef | grep motion-mmal | awk '{print $2}' | xargs kill

note: I put the script above in a code block as wordpress changes the quotes to smart ones otherwise which don’t work if you copy and paste

type ctrl+o then push the return key to write the text, followed by ctrl+x to exit the editor
chmod 755 stopmotion to make it executable

now you can type ./startmotion to start the camera and ./stopmotion to stop it
The videos created are stored in the m-video in the mmal home directory and the process is logged in the motion.log file
The command used in the start motion script was suggested by adayforgotten in the original topic thread. As you have seen, if you type the ./motion-mmal command to start the camera directly you cannot type subsequent commands into the terminal, and if you type ctrl+c or exit the terminal then the process terminates. Wrapping the command in nohup……& makes it run in the background and be independent of the terminal closing, which would normally stop dependent processes  The >/dev/null redirects the standard output to /dev/null, throwing it away. The “2>&1″ part redirects the “standard error” output of the command to the standard output. the “</dev/null” unattaches the console keyboard and uses “</dev/null” instead. Thus the script can start the process without producing any screen output.
The stopmotion script uses ps-ef to give a formatted list the process id of running processes, pipes the output to grep to find the line for the process motion-mmal pipes that to awk ‘{print $2}’ which extracts the second field or process ID and finally pipes to xargs which feeds in turn any matching ID to kill which terminates them. It is instructive to build up this command line manually trying each step in turn. Thus
ps -ef
ps -ef |grep motion-mmal
ps -ef | grep motion-mmal | awk ‘{print $2}’
etc to see the output of each stage in turn (you should have the process running first of course!)

Connecting the the Synology NAS surveillance module
If you have such a NAS you can log in to it with a web browser and start the supplied surveillance station. The trick is in how to setup the camera configuration.
The photo below shows the settings which have to be entered
pi-cam1

Although the frame rate is rather slow, the system works and in the time line of the Surveillance program you can inspect video where there has been motion detected.
The surveillance program has a full help file.

Quck install files
I have put the start and stop scripts plus my amended motion-mmalcam.conf file in a zip file which you can download here into your Pi home directory using

wget http://r.newman.ch/mmal-bits.zip
followed by unzip mmal-bits.zip
quick install instructions are included in a README file

45 thoughts on “Setting up Wireless motion-detect cam

  1. Very handy writeup, thank you! I set my configuration to 640×480 resolution and 3 fps. That works, and the AVI generated by motion-mmal as you describe can be played by VirtualDub 1.9.11 on Windows XP, but it always gives me the following warnings:

    [!] AVI: Index not found or damaged — reconstructing via file scan.
    [!] AVI: Keyframe flag reconstruction was not specified in open options and
    the video stream is not a known keyframe-only type. Seeking in the video
    stream may be extremely slow.

  2. Thanks for this tutorial. It’s been a huge help.

    However, I had issues with the stopmotion script. Is there any reason why one can’t simply use:

    #!/bin/sh
    killall motion-mmal

    It seems to work well for me.

  3. Thank you very much for this fantastic approach.
    I have a problem with the movies which are stored in /home/pi/m-video/.
    Is it possible to deactivate this feature and that only the streaming-function is working? Is there a parameter in motion-mmalcam.conf which can disable saving movies?

    • I’ll try and check for you. I think there may be something on this on the thread on MMAL on the Raspberry Pi Forum. Even if you can’t stop them, you could add a script to delete the oldest if space is an issue.

  4. Is there a restriction on the 640×480 size here? The pi cam can do full HD.

    I’m experiencing some stability issues with motion (with USB camera) but can get 720p quality currently… May be I should reduce to this lower resolution too.

    • Hi Mike
      The originator of the MMAL thread on raspberrypi.org …

      dozencrows wrote:
      A note on image resolution…

      Currently, only certain resolutions work. My personal testing has shown the following work:

      352×288
      640×480
      1024×576

      Hope this helps

  5. Thanks for the tutorial, it works really well, except it doesn’t use my raspberry pi camera board, instead it uses my usb camera. Is there a way I can select to use the camera board instead?

  6. Hi
    Thanks for the tutorial. I was having a bit of trouble setting this up before but starting from scratch using your tutorial has made it easier.
    FYI It looks like (so far at any rate) setting ffmpeg_output_movies to “off” in motion-mmalcam.conf will stop generation of avi files in the m-video directory.

  7. Hi, i’ve been having loads of problems recently with motion, i managed to set it up with a webcam a while back and have it working, but last monday started again with this project and nothing is working, webcam doesnt stream… I had several model of webcam and the board cam which is why im here trying with this as i tought it might be better to troubleshoot with this. it is generating videos on m-video folder but its not streaming, when i go IP:8081 what could I try to find out whats going wrong?

    thanks.

  8. By me the ./stopmotion command dont work…the error: awk: 1: unexpected character 0xe2
    Then i see in nano the quotes are not right. When you copy/paste from wordpress to nano is not the same.

    WordPress seems to be messing up the single and double quotes, you need to remove them and retype them in.

    • Well it does say type in the article not copy and paste. I didn’t put it in a code block where it would have copied ok.
      There is always the option of using the download for the files.
      I’ll see if I can alter it so it will copy and paste ok.

      • put this script in a code block so you CAN copy and paste it ok. Previously wordpress altered the quotes to smart ones which dont’ work.
        Thanks for the comment John

  9. Wonderful manual (in particular if I compare it to the almost stupid stuff that is copy-and-pasted elsewhere). Still, I get a problem. My log says

    [-1242889376] [NTC] [ALL] [Nov 09 22:14:28] motion_startup: Using log type (ALL) log level (WRN)
    [1] [ALR] [VID] [Nov 09 22:14:28] mmalcam_start: MMAL Camera thread starting… for camera (vc.ril.camera) of 1024 x 576 at 2 fps
    [1] [ALR] [VID] [Nov 09 22:14:28] mmalcam_start: MMAL Camera using video capture
    [0] [ERR] [ALL] [Nov 09 22:14:58] main: Thread 1 – Watchdog timeout, trying to do a graceful restart
    [0] [ERR] [ALL] [Nov 09 22:15:10] main: Thread 1 – Watchdog timeout, did NOT restart graceful,killing it!
    [0] [ERR] [ALL] [Nov 09 22:15:58] main: Thread 1 – Watchdog timeout, did NOT restart graceful,killing it!
    [0] [ALR] [VID] [Nov 09 22:15:58] MMAL Camera cleanup
    [1] [ALR] [VID] [Nov 09 22:15:59] mmalcam_start: MMAL Camera thread starting… for camera (vc.ril.camera) of 1024 x 576 at 2 fps
    [1] [ALR] [VID] [Nov 09 22:15:59] mmalcam_start: MMAL Camera using video capture
    [0] [ERR] [ALL] [Nov 09 22:16:28] main: Thread 1 – Watchdog timeout, trying to do a graceful restart…

    Any idea what is going on here?

  10. Hi! Thank you a lot for this very simple tutorial. It’s so simple that I can’t get motion working…

    I d’ont use yet the scripts to start and stop the stream. So I type this :
    ./motion-mmal -n -c motion-mmalcam.conf

    And it stay stuck here :
    [-1242705056] [NTC] [ALL] conf_load: Processing thread 0 – config file motion-mmalcam.conf
    [-1242705056] [NTC] [ALL] motion_startup: Motion mmaltest Started
    [-1242705056] [NTC] [ALL] motion_startup: Logging to file (/home/pi/MMAL/motion.log)

    Safari can’t access to the server when typing http://(RPIaddress):8081

    The motion-mmalcam is very close to yours.

    Did I missed something?

    Here is the result of raspistill -v -o temp.jpg :

    raspistill Camera App v1.3.5

    Width 2592, Height 1944, quality 85, filename temp.jpg
    Time delay 5000, Raw no
    Thumbnail enabled Yes, width 64, height 48, quality 35
    Link to latest frame enabled no
    Full resolution preview No
    Capture method : Single capture

    Preview Yes, Full screen Yes
    Preview window 0,0,1024,768
    Opacity 255
    Sharpness 0, Contrast 0, Brightness 50
    Saturation 0, ISO 0, Video Stabilisation No, Exposure compensation 0
    Exposure Mode ‘auto’, AWB Mode ‘auto’, Image Effect ‘none’
    Metering Mode ‘average’, Colour Effect Enabled No with U = 128, V = 128
    Rotation 0, hflip No, vflip No
    ROI x 0.000000, y 0.000000, w 1.000000 h 1.000000

    Thank you for your help.

  11. This tutorial is the best so far, short and understandable. One question. If I error and send
    ./startmotion again after motion is already running, ./stopmotion will not work. I tried a several times to stop, but could not. Had to do shutdown.

  12. when I try to build motion with config file I get error
    ioctl (VIDEOCGCAP): Invalid argument in motion

    Can you please help me figure what am I doing wrong ?

    • Not sure you should be trying to build motion…This article is written around a cuastomised downloadable binary. However, you should follow the renaming I describe to make sure you are using the correct binary, as you also install the standard motion to get the supporting files. The config file will only work with the customised motion binary that you download as described.

  13. Installed, start and stop files work but I haven’t got in the stream on Google+ Safari, VNC viewer or RDP, After a few minutes of it running it knocked out my lan connection so I couldn’t connect even with Putty which I had running at the time, the camera light is still on and the single red power light on the board. I pulled out my cat5 and re–inserted but it didn’t re-connect so I pulled the power and rebooted, now going for a re-run, booted ok cd mmal ./startmotion and it’s running again. Rfb protocol error on VNC, i’m now trying VLC via loads of reading on Google.

  14. Hello, thanks for the tutorial it worked first time :-)

    Is there any chance you would know how to get the PI to automatically start motion on boot. This would help for power outages and reboots etc

      • Hello RBN2013,
        Unfortunately it doesn’t appear to be so easy. I have added
        (sleep10;su – pi -c”/home/pi/mmal/startmotion”)&
        to my rc.local and when I log in and “top” motion-mmal is running however there is no light on the camera board and no webpage displaying the output. If I then ./stopmotion and ./startmotion everything works.

        I note that the startup text says
        [warn] Not starting motion daemon, disabled via /etc/default/motion /// (warning)
        However I believe this is generated by the motion package and not MMAL motion package. If I edit this file to say yes plain old motion starts.

        Do I need to add the user system to any groups or anything like that and if so how?

        Thanks
        Steve

      • It looks as if the mmal package is not starting. You shouldn’t have to change any groups. I changed the name of the modified package to motion-mmal and the conf file specifically to avoid confusion between the installed motion package and the modified version and used ./motion-mmal -n -c motion-mmalcam.conf to start things. It looks as if the correct one is not starting.

      • Thanks rbn2013,
        I did as you suggested and used ./motion-mmal -n -c motion-mmalcam.conf in my rc.local This piped the error messages to the command prompt (making it unusable so I had to SSH in, but it was very good feedback for debugging).

        I am not sure if it was a problem but I discovered that I had “Start in Deamon” as “on” in both the mmal conf file and the standard one (I turned them back off).

        Furthermore I discovered that I had to give the explicit location of the conf file in the RC.Local and not just the file name. If motion can not oped the specified conf file it will use the default one.

        So if you don’t tinker with anything you should just be able to add the following line to the RC.local for it to start automatically.
        (sleep 4;su – pi -c “/home/pi/mmal/motion-mmal -n -c /home/pi/mmal/motion-mmalcam.conf”)&

        Thanks again

  15. Thanks for the clear explanation of how to set this up. I have it all working however it is very slow with about a ten second delay between the actual motion and that being streamed. Any idea how I could fix this?

  16. Hi,
    I tried this and was able to finally get motion up and working and that was great. But after a few image captures by motion detection the images cease to be captured. . maybe a few minutes and no more images or videos are saved. There is plenty of disk space, the motion process is still running and the people pi noir cam LED continues to remain lit. I don’t want to introduce another process to restart motion. Can you offer any advice?

    • Hi there
      I wrote this project last July so I’m afraid I am a bit rusty about it now. I suggest you ask the question on the original Raspberry Pi forum article linked at the beginning of the article.

  17. Hi, this app detects motion as a picture change. So if it is dark and someone enters the camera field he/she won’t be detected. There is no real intruder detection. So it is completely useless as a security camera since burglars wouldn’t normally switch on the light when they break in. Would be nice to add the capability of using a GPIO input as another triggering method using a real infrared intruder detector.

  18. I tried this on 20/1/14, but the .tar file is not available on Dropbox. Is there an alternative, or has it been moved please.

  19. Back again – I installed the software and modified the .conf file as specified. The camera red light was already on, having tried to check the view previously from Firefox, so I re-booted it – still on. When I try the program, I get an error message:
    mmal: mmal_vc_component_enable: failed to enable component: ENOSPC
    Segmentation fault
    If you can give me any idea what I have done wrong, I would appreciate it.

    • I’m a bit rusty on this Nigel. Haven’t looked at it for months. I’ll see if I have time to check it out again. BTW there have just been advances in the camera software. Have a look at this. May be of interest. I did some slow mo movies of water drops falling yesterday. Very nice.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s