.. note:: Hello, welcome to the SunFounder Raspberry Pi & Arduino & ESP32 Enthusiasts Community on Facebook! Dive deeper into Raspberry Pi, Arduino, and ESP32 with fellow enthusiasts. **Why Join?** - **Expert Support**: Solve post-sale issues and technical challenges with help from our community and team. - **Learn & Share**: Exchange tips and tutorials to enhance your skills. - **Exclusive Previews**: Get early access to new product announcements and sneak peeks. - **Special Discounts**: Enjoy exclusive discounts on our newest products. - **Festive Promotions and Giveaways**: Take part in giveaways and holiday promotions. 👉 Ready to explore and create with us? Click [|link_sf_facebook|] and join today! .. _4.1.4_py: 4.1.4 Automatic Capture Camera =================================== Introduction ----------------- When you are out, the little squirrels in the woods might visit your windowsill. Let's make a automatic capture camera to leave pictures of these little cuties! Required Components ------------------------------ In this project, we need the following components. .. image:: ../img/3.1.18components.png :width: 800 :align: center It's definitely convenient to buy a whole kit, here's the link: .. list-table:: :widths: 20 20 20 :header-rows: 1 * - Name - ITEMS IN THIS KIT - LINK * - Raphael Kit - 337 - |link_Raphael_kit| You can also buy them separately from the links below. .. list-table:: :widths: 30 20 :header-rows: 1 * - COMPONENT INTRODUCTION - PURCHASE LINK * - :ref:`cpn_gpio_board` - |link_gpio_board_buy| * - :ref:`cpn_breadboard` - |link_breadboard_buy| * - :ref:`cpn_wires` - |link_wires_buy| * - :ref:`cpn_resistor` - |link_resistor_buy| * - :ref:`cpn_camera_module` - |link_camera_buy| * - :ref:`cpn_pir` - \- Schematic Diagram ----------------------- ============ ======== ======== === T-Board Name physical wiringPi BCM GPIO17 Pin 11 0 17 ============ ======== ======== === .. image:: ../img/1.1.18_schematic.png :width: 400 :align: center Experimental Procedures ------------------------------ Before this project, you need to make sure you complete :ref:`3.1.1_py` . **Step 1:** Build the circuit. .. image:: ../img/3.1.18fritzing.png :width: 800 :align: center **Step 2:** To connect the camera module and complete the configuration, please refer to: :ref:`cpn_camera_module`. **Step 3:** Go into the Raspberry Pi Desktop. You may need a screen for a better experience, refer to: `Connect your Raspberry Pi `_. Or access the Raspberry Pi desktop remotely, for a detailed tutorial please refer to :ref:`remote_desktop`. **Step 4:** Open a Terminal and get into the folder of the code. .. raw:: html .. code-block:: cd ~/raphael-kit/python/ **Step 5:** Run. .. raw:: html .. code-block:: sudo python3 4.1.4_AutomaticCaptureCamera.py After the code runs, PIR will detect the surrounding environment, and if it senses the little squirrel passing by, the camera will take a photo. The photo interval is 3 seconds, and the total number of photos taken will be displayed through the print window. There are two potentiometers on the PIR module: one is to adjust sensitivity and the other is to adjust the detection distance. To make the PIR module work better, you You need to turn both of them counterclockwise to the end. .. image:: ../img/PIR_TTE.png :width: 400 :align: center .. note:: You can also open ``4.1.4_AutomaticCaptureCamera.py`` in the ``~/raphael-kit/python/`` path with a Python IDE, click Run button to run, and stop the code with Stop button. **Code** .. note:: You can **Modify/Reset/Copy/Run/Stop** the code below. But before that, you need to go to source code path like ``raphael-kit/python``. After modifying the code, you can run it directly to see the effect. .. raw:: html .. code-block:: python #!/usr/bin/env python3 import time import os import RPi.GPIO as GPIO from picamera2 import Picamera2 # ---------------------------- # USER DIRECTORY # ---------------------------- user = os.getlogin() user_home = os.path.expanduser(f'~{user}') # ---------------------------- # GPIO SETUP # ---------------------------- PIR_PIN = 17 # PIR motion sensor connected to GPIO17 GPIO.setmode(GPIO.BCM) GPIO.setup(PIR_PIN, GPIO.IN, pull_up_down=GPIO.PUD_DOWN) # ---------------------------- # CAMERA SETUP # ---------------------------- camera = Picamera2() camera.start() print("Motion detection started. Press Ctrl+C to exit.") # ---------------------------- # MAIN LOOP # ---------------------------- try: i = 1 while True: if GPIO.input(PIR_PIN) == GPIO.HIGH: filename = f"{user_home}/capture{i}.jpg" camera.capture_file(filename) print(f"Motion detected. Saved image #{i}: {filename}") time.sleep(3) i += 1 else: print("waiting") time.sleep(0.5) # ---------------------------- # KEYBOARD INTERRUPT # ---------------------------- except KeyboardInterrupt: print("\nKeyboard interrupt received. Exiting program...") # ---------------------------- # CLEANUP # ---------------------------- finally: try: camera.close() except: pass GPIO.cleanup() print("Program exited cleanly.") **Code Explanation** #. Reads the current user's home directory for saving captured images. .. code-block:: python user = os.getlogin() user_home = os.path.expanduser(f'~{user}') This obtains the active user's name and builds a full path to the home directory. #. Sets up GPIO and configures the PIR motion sensor on ``GPIO17`` as an input. .. code-block:: python PIR_PIN = 17 GPIO.setmode(GPIO.BCM) GPIO.setup(PIR_PIN, GPIO.IN, pull_up_down=GPIO.PUD_DOWN) Using a pull-down resistor ensures that the pin reads ``LOW`` when no motion is detected. #. Initializes the Picamera2 instance and starts the camera. .. code-block:: python camera = Picamera2() camera.start() The camera is activated so it can capture images immediately when motion is detected. #. Detects motion by reading the PIR sensor input state. .. code-block:: python if GPIO.input(PIR_PIN) == GPIO.HIGH: When the PIR senses movement, it outputs a ``HIGH`` signal, triggering the capture process. #. Captures an image and saves it using a sequential file number. .. code-block:: python filename = f"{user_home}/capture{i}.jpg" camera.capture_file(filename) Each detection saves a new image as ``capture1.jpg``, ``capture2.jpg``, and so on. #. Delays for three seconds after a motion-triggered capture. .. code-block:: python time.sleep(3) This prevents multiple images from being taken too quickly after a single motion event. #. Prints “waiting” when no motion is detected and checks again after a short delay. .. code-block:: python else: print("waiting") time.sleep(0.5) This ensures constant monitoring while reducing unnecessary CPU usage. #. Handles keyboard interruption (Ctrl+C) to exit the program safely. .. code-block:: python except KeyboardInterrupt: print("\nKeyboard interrupt received. Exiting program...") A clean exit message is printed when the user stops the program manually. #. Releases camera and GPIO resources before exiting. .. code-block:: python finally: camera.close() GPIO.cleanup() This ensures the camera shuts down properly and all GPIO pins return to a safe state. Phenomenon Picture ------------------------ .. image:: ../img/4.1.4spycamera.JPG :align: center