Motion-activated scripts in Linux
One of the most frequent requests I receive for help in the Linux command line is actually for a little setup I generally use for pranks. Using the program Motion, you can run a bash script any time a webcam detects movement (among many, many other useful things). The uses for this are, as you can imagine, endless–especially if you get your setup running so that shell scripts can activate pins on an Arduino, but more on that in a later post.
I thought I’d share the setup and even put a useful twist on it. Let’s assume you have something cool you’d like to show information about, like a 3D printer. You make a neat looping slideshow about how it works and what sorts of things it can make. That’s not good enough, though. Say you’d like to give people a better view of what’s happening right at the print head whenever it starts moving. Let’s turn this prank setup into something that can launch a full-screen view onto that monitor whenever motion is detected, and then go back to your slideshow when the motion ends!
The Setup
First, ensure that you have two USB webcams. There are ways to do this with just one (there’s a way to do everything), but since the camera will already be opened directly by Motion, you won’t be able to open it directly from any other program. You’ll need to think of a workaround like streaming out a port, then opening the network stream into a video window.
Next, install motion and xawtv (I’m assuming a Debian-based distribution here. These first two commands will be slightly different on RPM-based distributions like Red Hat and OpenSUSE):
Navigate to home if you’re not already there:
Create a shell script called startCam.sh (whatever editor you prefer—use nano if you don’t know vi):
Fill it with this code (ignore the tilde at the bottom—that just signifies a blank line):
Save the file, then make it executable like so:
Now create a shell script called stopCam.sh and fill it with this code:
Make it executable as well.
Now open motion.conf. We need to make a few changes in here, all of which can be edited later to give us abilities like streaming the motion camera on a certain port.
Set your gap to however many seconds after the print heads stop moving you’d like to turn off the display camera and return to whatever is on the screen (like a slideshow):
Turn off output_normal. We don’t want to clutter up the memory with random security footage:
Disable ffmpeg_cap_new for the same reason:
Disable the webcam server:
Disable HTTP control of motion:
Now we’re ready to link to the scripts. Find this block in the config:
Remove the “;”s before each line so that they’re activated, then replace their values with the path to the scripts we made earlier:
Now, to start it up, ensure that two cameras are connected over USB and then type this command: