.. note::

    Hola, ¡bienvenido a la Comunidad de Entusiastas de SunFounder para Raspberry Pi, Arduino y ESP32 en Facebook! Sumérgete en el mundo de Raspberry Pi, Arduino y ESP32 con otros entusiastas.

    **¿Por qué unirse?**

    - **Soporte experto**: Resuelve problemas postventa y desafíos técnicos con la ayuda de nuestra comunidad y equipo.
    - **Aprende y comparte**: Intercambia consejos y tutoriales para mejorar tus habilidades.
    - **Previsualizaciones exclusivas**: Obtén acceso anticipado a nuevos anuncios de productos y adelantos.
    - **Descuentos especiales**: Disfruta de descuentos exclusivos en nuestros productos más recientes.
    - **Promociones y sorteos festivos**: Participa en sorteos y promociones durante las festividades.

    👉 ¿Listo para explorar y crear con nosotros? Haz clic en [|link_sf_facebook|] y únete hoy mismo.

.. _1.3.2_py_pi5:

1.3.2 Servomotor
===================

Introducción
----------------

En este proyecto, aprenderemos cómo hacer que el servomotor gire.

Componentes necesarios
---------------------------

En este proyecto, necesitamos los siguientes componentes. 

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

Es definitivamente conveniente comprar un kit completo, aquí está el enlace: 

.. list-table::
    :widths: 20 20 20
    :header-rows: 1

    *   - Nombre	
        - ELEMENTOS EN ESTE KIT
        - ENLACE
    *   - Kit Raphael
        - 337
        - |link_Raphael_kit|

También puedes comprarlos por separado en los enlaces a continuación.

.. list-table::
    :widths: 30 20
    :header-rows: 1

    *   - INTRODUCCIÓN DEL COMPONENTE
        - ENLACE DE COMPRA

    *   - :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|

Diagrama esquemático
-------------------------

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


Procedimientos experimentales
-----------------------------

**Paso 1:** Construye el circuito.

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

**Paso 2**: Ve a la carpeta del código.

.. raw:: html

   <run></run>

.. code-block::

    cd ~/raphael-kit/python-pi5

**Paso 3**: Ejecuta el archivo ejecutable.

.. raw:: html

   <run></run>

.. code-block::

    sudo python3 1.3.2_Servo_zero.py

Después de ejecutar el programa, el servomotor girará de 0 grados a 90 a 180 grados, y luego de 180 grados a 90 a 0 grados, en un ciclo.

.. warning::

    Si recibe el mensaje de error ``RuntimeError: Cannot determine SOC peripheral base address``, consulte :ref:`faq_soc`

**Código**

.. note::

    Puedes **Modificar/Reiniciar/Copiar/Ejecutar/Detener** el código a continuación. Pero antes de eso, debes ir a la ruta del código fuente como ``raphael-kit/python-pi5``. Después de modificar el código, puedes ejecutarlo directamente para ver el efecto.

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

**Explicación del Código**

#. Estas declaraciones de importación traen la clase ``Servo`` para el control del servomotor y la función ``sleep`` para la temporización.

   .. code-block:: python

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

#. Establece el número de pin GPIO 18 para conectar el servomotor.

   .. code-block:: python

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

#. Estas líneas definen un factor de corrección y lo utilizan para calcular las anchuras de pulso máximas y mínimas para el servo, ajustando su rango de movimiento.

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

#. Inicializa el objeto Servo con el pin GPIO especificado y anchos de pulso personalizados.

   .. code-block:: python

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

#. El bloque ``try`` contiene un bucle ``while True`` para mover continuamente el servo. El servo se posiciona en los puntos medio, mínimo y máximo, con cada posición impresa y mantenida durante una duración especificada.

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

