.. note:: Bonjour et bienvenue dans la Communauté Facebook des passionnés de Raspberry Pi, Arduino et ESP32 de SunFounder ! Plongez plus profondément dans l'univers des Raspberry Pi, Arduino et ESP32 avec d'autres passionnés. **Pourquoi rejoindre ?** - **Support d'experts** : Résolvez les problèmes après-vente et les défis techniques avec l'aide de notre communauté et de notre équipe. - **Apprendre et partager** : Échangez des astuces et des tutoriels pour améliorer vos compétences. - **Aperçus exclusifs** : Accédez en avant-première aux annonces de nouveaux produits et aux aperçus. - **Réductions spéciales** : Profitez de réductions exclusives sur nos produits les plus récents. - **Promotions festives et cadeaux** : Participez à des cadeaux et des promotions de vacances. 👉 Prêt à explorer et à créer avec nous ? Cliquez [|link_sf_facebook|] et rejoignez-nous aujourd'hui ! .. _4.1.1_py: 4.1.1 Appareil photo ============================ Introduction ----------------- Ici, nous allons fabriquer un appareil photo avec un déclencheur. Lorsque vous appuyez sur le bouton, l'appareil photo prend une photo pendant que la LED clignote. Composants nécessaires ------------------------------ Dans ce projet, nous avons besoin des composants suivants. .. image:: ../img/3.1.15camera_list.png :width: 800 :align: center Il est certainement pratique d'acheter un kit complet, voici le lien : .. list-table:: :widths: 20 20 20 :header-rows: 1 * - Nom - ÉLÉMENTS DANS CE KIT - LIEN * - Kit Raphael - 337 - |link_Raphael_kit| Vous pouvez également les acheter séparément aux liens ci-dessous. .. list-table:: :widths: 30 20 :header-rows: 1 * - INTRODUCTION DES COMPOSANTS - LIEN D'ACHAT * - :ref:`cpn_gpio_extension_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_led` - |link_led_buy| * - :ref:`cpn_button` - |link_button_buy| * - :ref:`cpn_camera_module` - |link_camera_buy| Schéma de câblage ----------------------- ============ ======== ======== === Nom T-Board physique wiringPi BCM GPIO17 Pin 11 0 17 GPIO18 Pin 12 1 18 ============ ======== ======== === .. image:: ../python_pi5/img/4.1.1_camera_schematic.png :align: center Procédures expérimentales ------------------------------ **Étape 1 :** Construire le circuit. .. image:: ../python_pi5/img/4.1.1_camera_circuit.png :width: 800 :align: center **Étape 2 :** Pour connecter le module caméra et compléter la configuration, veuillez vous référer à : :ref:`cpn_camera_module`. **Étape 3 :** Accédez au bureau de la Raspberry Pi. Vous aurez peut-être besoin d'un écran pour une meilleure expérience, référez-vous à : `Connect your Raspberry Pi `_. Ou accédez au bureau de la Raspberry Pi à distance, pour un tutoriel détaillé, veuillez vous référer à : :ref:`remote_desktop`. **Étape 4 :** Ouvrez un terminal et accédez au dossier du code. .. raw:: html .. code-block:: cd ~/raphael-kit/python/ **Étape 5 :** Exécutez le code. .. raw:: html .. code-block:: sudo python3 4.1.1_Camera.py Après l'exécution du code, appuyez sur le bouton, la Raspberry Pi fera clignoter la LED et prendra une photo. La photo sera nommée ``my_photo.jpg`` et stockée dans le répertoire ``~``. .. note:: Vous pouvez également ouvrir ``4.1.1_Camera.py`` dans le chemin ``~/raphael-kit/python/`` avec un IDE Python, cliquer sur le bouton Run pour exécuter et sur le bouton Stop pour arrêter le code. Si vous souhaitez télécharger la photo sur votre PC, veuillez vous référer à : :ref:`filezilla`. **Code** .. note:: Vous pouvez **Modifier/Réinitialiser/Copier/Exécuter/Arrêter** le code ci-dessous. Mais avant cela, vous devez vous rendre dans le chemin du code source comme ``raphael-kit/python``. Après avoir modifié le code, vous pouvez l'exécuter directement pour voir l'effet. .. raw:: html .. code-block:: python #!/usr/bin/env python3 import time import os import RPi.GPIO as GPIO from picamera2 import Picamera2, Preview # ---------------------------- # GPIO SETUP # ---------------------------- BUTTON_PIN = 18 # The push button is connected to GPIO18 LED_PIN = 17 # The LED is connected to GPIO17 GPIO.setmode(GPIO.BCM) # Use BCM GPIO numbering # The button uses a 10K pull-up resistor externally. # When released → HIGH, when pressed → LOW. GPIO.setup(BUTTON_PIN, GPIO.IN, pull_up_down=GPIO.PUD_UP) # LED is an output (HIGH → ON, LOW → OFF) GPIO.setup(LED_PIN, GPIO.OUT) GPIO.output(LED_PIN, GPIO.LOW) # Ensure LED is OFF at startup # ---------------------------- # USER DIRECTORY SETUP # ---------------------------- # Get the current logged-in username user = os.getlogin() # Build the path to the user's home directory (ex: /home/pi) user_home = os.path.expanduser(f"~{user}") # ---------------------------- # CAMERA SETUP # ---------------------------- # Create a Picamera2 object camera = Picamera2() # Create a preview configuration: # main → the main camera stream # size → resolution 800x600 # format → display format used by the preview window preview_config = camera.create_preview_configuration( main={"size": (800, 600), "format": "XRGB8888"} ) # Apply the configuration to the camera camera.configure(preview_config) # Start the preview window using QTGL (GPU-accelerated) camera.start_preview(Preview.QTGL) # Start the camera hardware camera.start() print("Ready! Press the button to take a photo...") # ---------------------------- # MAIN LOOP # ---------------------------- try: while True: # Check if button is pressed (LOW means pressed) if GPIO.input(BUTTON_PIN) == GPIO.LOW: print("Button pressed! Taking photo...") # Flash LED 3 times to warn before taking the photo for _ in range(3): GPIO.output(LED_PIN, GPIO.HIGH) time.sleep(0.1) GPIO.output(LED_PIN, GPIO.LOW) time.sleep(0.1) # Build a unique filename using current date and time # Example: /home/pi/my_photo_20251201_143522.jpg timestamp = time.strftime("%Y%m%d_%H%M%S") filename = os.path.join(user_home, f"my_photo_{timestamp}.jpg") # Capture the image camera.capture_file(filename) print(f"Photo saved to: {filename}") # Turn LED ON briefly to confirm capture GPIO.output(LED_PIN, GPIO.HIGH) time.sleep(0.5) GPIO.output(LED_PIN, GPIO.LOW) # Debounce delay to prevent repeated triggers time.sleep(0.3) # Small delay to reduce CPU usage time.sleep(0.01) # ---------------------------- # CLEAN EXIT WHEN CTRL+C IS PRESSED # ---------------------------- except KeyboardInterrupt: print("\nCtrl+C received, exiting...") # ---------------------------- # CLEANUP SECTION # ---------------------------- finally: # Safely try to stop the camera preview try: camera.stop_preview() except: pass # Ignore errors if preview wasn't running # Safely close the camera device try: camera.close() except: pass # Reset GPIO pins to a safe state GPIO.cleanup() print("Program exited cleanly.") **Explication du code** #. Vérifie si le bouton connecté à ``BUTTON_PIN`` est pressé. .. code-block:: python if GPIO.input(BUTTON_PIN) == GPIO.LOW: Comme le bouton utilise une résistance de tirage vers le haut (pull-up), son état par défaut est ``HIGH``. Lorsque le bouton est pressé, le signal devient ``LOW`` et déclenche le processus de capture d’image. #. Fait clignoter la LED trois fois comme retour visuel avant de prendre une photo. .. code-block:: python for _ in range(3): GPIO.output(LED_PIN, GPIO.HIGH) time.sleep(0.1) GPIO.output(LED_PIN, GPIO.LOW) time.sleep(0.1) Cela indique que le Raspberry Pi se prépare à capturer une image. #. Génère un nom de fichier unique à l’aide d’un horodatage et capture une photo. .. code-block:: python timestamp = time.strftime("%Y%m%d_%H%M%S") filename = os.path.join(user_home, f"my_photo_{timestamp}.jpg") camera.capture_file(filename) L’horodatage garantit que chaque photo capturée possède un nom différent. L’image est ensuite enregistrée dans le répertoire personnel de l’utilisateur. #. Allume la LED pendant 0,5 seconde pour confirmer qu’une photo a été prise. .. code-block:: python GPIO.output(LED_PIN, GPIO.HIGH) time.sleep(0.5) GPIO.output(LED_PIN, GPIO.LOW) Cette brève illumination signale que la capture a réussi. #. Ajoute un court délai pour éviter plusieurs déclenchements lors d’un seul appui sur le bouton. .. code-block:: python time.sleep(0.3) Ce délai d’antirebond assure un fonctionnement fiable du bouton. Photo du Phénomène ------------------------ .. image:: ../img/4.1.1camera.JPG :align: center