Trigger a Webcam With a Button and Raspberry Pi

by JoseBarreiros in Circuits > Raspberry Pi

33770 Views, 167 Favorites, 0 Comments

Trigger a Webcam With a Button and Raspberry Pi

IMG_3701.JPG

This instructable will show how to trigger a webcam using Raspberry and a push button. A bash script run at startup and it launch a Python script that survey the GPIO port. When the button is pressed, a "fswebcam" command runs.

Materials

Pi2ModB1GB_-comp.jpeg
5megapixel-Cmos-usb-2-0-android-external-usb-camera-for-android-ELP-USB500W02M-L36.jpg
BUTT-2_4.jpg
cable-macho-hembra-idea-arduino-y-protoboard-13086-MLA20070791180_032014-F.jpg

- Raspberry Pi 2 Model B

- Webcam (Make sure your camera is UVC complain)

- Push Button

- Breadboard

- Cables

Wiring

IMG_3700.JPG
j8header-photo.png
raspberry-pi-rev2-gpio-pinout.jpg
2015-08-30-072634_1232x992_scrot.png

- Connect the push button to the GPIO pins: GPIO15 (pin 12) and GND (pin 6).

- Connect the Webcam to a USB port.

To make sure your camera was recognized, list the devices with:

$cd /dev/

$ls

Your camera should be listed as /video*

Creating Your Program in Python

2015-08-29-174132_1232x992_scrot.png
2015-08-29-174541_1232x992_scrot.png

Open a window in Python 3: Menu>Programming>Python 3>File>New Window

Copy the following code and Save As /home/pi/camerascript.py

import subprocess

import RPi.GPIO as GPIO

import time

GPIO.setmode(GPIO.BOARD)

GPIO.setup(12, GPIO.IN, pull_up_down=GPIO.PUD_UP)

i=0

try:

while True:

input_state = GPIO.input(12)

if input_state == 0:

subprocess.call("fswebcam -d /dev/video0 -r 1024x768 -S0 "+str(i)+"pic.jpg",shell=True) print('PIC CAPTURED')

i=i+1

time.sleep(0.2)

except KeyboardInterrupt:

GPIO.cleanup()

Bash Script

2015-08-29-174701_1232x992_scrot.png
2015-08-29-175012_1232x992_scrot.png

Open the terminal and run:

$nano bashscript.sh

Add the following lines to /home/pi/bashscript.sh

#!/bin/bash

echo Launching camera

sudo python camerascript.py

Make Your Script Executable and Run at Startup

2015-08-29-175455_1232x992_scrot.png
2015-08-29-175653_1232x992_scrot.png
2015-08-29-175821_1232x992_scrot.png
2015-08-29-180132_1232x992_scrot.png

First, give make your bash script executable:

$chmod ugo +x /home/pi/bashcript.sh

Second, type $nano ~/.bashrc ,and add the following lines at the end of the file to make your script run at startup:

#run startup script

echo .bash running

bash bashscript.sh

Third, autologin as pi user:

$sudo nano /etc/inittab

Comment this line: 1:2345:respawn:/sbin/getty --noclear 38400 tty1

Add this line: 1:2345:respawn:/bin/login -f pi tty1 /dev/tty1 2>&1

Finally, reboot your Pi

$sudo reboot

Results

Webcam trigger with a button and Raspberry Pi
FDCC3XFIDYKDI7R.jpeg

Push the button, wait for the trigger and check if a new jpeg file was created in /home/pi/

Have fun.
Thanks for reading.