 
.. 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 !

.. _1.3.2_py_pi5:

1.3.2 Servo
===============

Introduction
-------------------

Dans ce projet, nous allons apprendre à faire tourner un servo.

Required Components
-----------------------------------

Dans ce projet, nous avons besoin des composants suivants. 

.. image:: ../python_pi5/img/1.3.2_servo_list.png

Il est très 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 à partir des 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_servo`
        - |link_servo_buy|

Schematic Diagram
----------------------

.. image:: ../img/image337.png


Experimental Procedures
---------------------------

**Étape 1 :** Construisez le circuit.

.. image:: ../img/image125.png

**Étape 2 :** Accédez au dossier du code.

.. raw:: html

   <run></run>

.. code-block::

    cd ~/raphael-kit/python-pi5

**Étape 3 :** Exécutez le fichier exécutable.

.. raw:: html

   <run></run>

.. code-block::

    sudo python3 1.3.2_Servo_zero.py

Après l'exécution du programme, le servo tournera de 0 degrés à 90 degrés à 180 degrés, puis de 180 degrés à 90 degrés à 0 degrés, en cercle.

.. warning::

    Si vous recevez le message d'erreur ``RuntimeError: Cannot determine SOC peripheral base address``, veuillez consulter :ref:`faq_soc`

**Code**

.. note::

    Vous pouvez **Modifier/Réinitialiser/Copier/Exécuter/Arrêter** le code ci-dessous. Mais avant cela, vous devez accéder au chemin source du code comme ``raphael-kit/python-pi5``. Après avoir modifié le code, vous pouvez l'exécuter directement pour voir l'effet.


.. raw:: html

    <run></run>

.. code-block:: python

   #!/usr/bin/env python3
   from gpiozero import Servo
   from time import sleep

   # Set the GPIO pin number where the servo motor is connected
   myGPIO = 18

   # Define a correction factor to fine-tune servo pulse width
   myCorrection = 0.45
   maxPW = (2.0 + myCorrection) / 1000  # Calculate maximum pulse width
   minPW = (1.0 - myCorrection) / 1000  # Calculate minimum pulse width

   # Initialize the Servo object with custom pulse widths
   servo = Servo(myGPIO, min_pulse_width=minPW, max_pulse_width=maxPW)

   try:
       while True:
           # Position the servo at the middle and wait
           servo.mid()
           print("mid")  # Indicate current position
           sleep(0.5)    # Brief pause for 0.5 seconds

           # Move the servo to its minimum position and wait
           servo.min()
           print("min")  # Indicate current position
           sleep(1)      # Hold position for 1 second

           # Return the servo to the middle position and wait
           servo.mid()
           print("mid")  # Indicate current position
           sleep(0.5)    # Brief pause for 0.5 seconds

           # Move the servo to its maximum position and wait
           servo.max()
           print("max")  # Indicate current position
           sleep(1)      # Hold position for 1 second

   except KeyboardInterrupt:
       # Gracefully terminate the script on a keyboard interrupt (Ctrl+C)
       pass


**Explication du Code**

#. Ces instructions d'importation incluent la classe ``Servo`` pour le contrôle du servo et la fonction ``sleep`` pour le timing.

   .. code-block:: python

       #!/usr/bin/env python3
       from gpiozero import Servo
       from time import sleep

#. Définit le numéro de la broche GPIO 18 pour connecter le moteur servo.

   .. code-block:: python

       # Set the GPIO pin number where the servo motor is connected
       myGPIO = 18

#. Ces lignes définissent un facteur de correction et l'utilisent pour calculer les largeurs d'impulsion maximales et minimales pour le servo, ajustant ainsi sa plage de mouvement.

   .. code-block:: python

       # Define a correction factor to fine-tune servo pulse width
       myCorrection = 0.45
       maxPW = (2.0 + myCorrection) / 1000  # Calculate maximum pulse width
       minPW = (1.0 - myCorrection) / 1000  # Calculate minimum pulse width

#. Initialise l'objet Servo avec la broche GPIO spécifiée et des largeurs d'impulsion personnalisées.

   .. code-block:: python

       # Initialize the Servo object with custom pulse widths
       servo = Servo(myGPIO, min_pulse_width=minPW, max_pulse_width=maxPW)

#. Le bloc ``try`` contient une boucle ``while True`` pour déplacer continuellement le servo. Le servo est positionné aux points milieu, min et max, chaque position étant imprimée et maintenue pendant une durée spécifiée.

   .. code-block:: python

       try:
           while True:
               # Position the servo at the middle and wait
               servo.mid()
               print("mid")  # Indicate current position
               sleep(0.5)    # Brief pause for 0.5 seconds

               # Move the servo to its minimum position and wait
               servo.min()
               print("min")  # Indicate current position
               sleep(1)      # Hold position for 1 second

               # Return the servo to the middle position and wait
               servo.mid()
               print("mid")  # Indicate current position
               sleep(0.5)    # Brief pause for 0.5 seconds

               # Move the servo to its maximum position and wait
               servo.max()
               print("max")  # Indicate current position
               sleep(1)      # Hold position for 1 second

       except KeyboardInterrupt:
           # Gracefully terminate the script on a keyboard interrupt (Ctrl+C)
           pass

