.. note:: ¡Hola! Bienvenido a la Comunidad de Entusiastas de SunFounder Raspberry Pi & Arduino & ESP32 en Facebook. Sumérgete más en Raspberry Pi, Arduino y ESP32 con otros entusiastas. **¿Por qué unirse?** - **Soporte Experto**: Resuelve problemas post-venta y desafíos técnicos con la ayuda de nuestra comunidad y equipo. - **Aprende y Comparte**: Intercambia consejos y tutoriales para mejorar tus habilidades. - **Avances Exclusivos**: Obtén acceso anticipado a anuncios de nuevos productos y adelantos. - **Descuentos Especiales**: Disfruta de descuentos exclusivos en nuestros productos más recientes. - **Promociones y Sorteos Festivos**: Participa en sorteos y promociones de temporada. 👉 ¿Listo para explorar y crear con nosotros? Haz clic en [|link_sf_facebook|] y únete hoy. .. _1.3.3_py_pi5: 1.3.3 Relé ============= Introducción ----------------- En este proyecto, aprenderemos a usar un relé. Es uno de los componentes más utilizados en los sistemas de control automático. Cuando el voltaje, la corriente, la temperatura, la presión, etc., alcanzan, superan o están por debajo del valor predeterminado, el relé conectará o interrumpirá el circuito, para controlar y proteger el equipo. Componentes Necesarios ------------------------- En este proyecto, necesitamos los siguientes componentes. .. image:: ../python_pi5/img/1.3.3_relay_list.png Es definitivamente conveniente comprar un kit completo, aquí está el enlace: .. list-table:: :widths: 20 20 20 :header-rows: 1 * - Nombre - COMPONENTES 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 DE COMPONENTES - ENLACE DE COMPRA * - :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_led` - |link_led_buy| * - :ref:`cpn_transistor` - |link_transistor_buy| * - :ref:`cpn_relay` - |link_relay_buy| * - :ref:`cpn_diode` - |link_diode_buy| Diagrama Esquemático ------------------------ .. image:: ../python_pi5/img/1.3.3_relay_schematic.png Procedimientos Experimentales -------------------------------- **Paso 1:** Construye el circuito. .. image:: ../python_pi5/img/1.3.3_relay_circuit.png **Paso 2:** Abre el archivo de código. .. raw:: html .. code-block:: cd ~/raphael-kit/python-pi5 **Paso 3:** Ejecuta. .. raw:: html .. code-block:: sudo python3 1.3.3_Relay_zero.py Mientras el código se está ejecutando, el LED se enciende. Además, puedes escuchar un tic-tac causado por la interrupción del contacto normalmente cerrado y el cierre del contacto normalmente abierto. .. warning:: Si recibe el mensaje de error ``RuntimeError: Cannot determine SOC peripheral base address``, consulte :ref:`faq_soc` **Código** .. note:: Puedes **Modificar/Restablecer/Copiar/Ejecutar/Detener** el código a continuación. Pero antes de eso, necesitas 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 .. code-block:: python #!/usr/bin/env python3 from gpiozero import OutputDevice # Import the class for controlling GPIO pins from time import sleep # Import the sleep function for delay # Initialize the relay connected to GPIO pin 17, starting in the 'off' state relay = OutputDevice(17, initial_value=False) try: # Loop to continuously toggle the relay's state every second while True: print('Relay open...') # Inform that the relay is being activated relay.on() # Turn on the relay (assuming active low configuration) sleep(1) # Maintain the relay in the on state for 1 second print('...Relay close') # Inform that the relay is being deactivated relay.off() # Turn off the relay sleep(1) # Maintain the relay in the off state for 1 second except KeyboardInterrupt: # Handle a keyboard interrupt (Ctrl+C) to exit the loop relay.off() # Ensure the relay is turned off before exiting pass **Explicación del Código** #. It imports ``OutputDevice`` from ``gpiozero`` for controlling GPIO pins and ``sleep`` from ``time`` for adding delays. .. code-block:: python #!/usr/bin/env python3 from gpiozero import OutputDevice # Import the class for controlling GPIO pins from time import sleep # Import the sleep function for delay #. Inicializa un objeto ``OutputDevice`` para el relé conectado al pin GPIO 17. El ``initial_value=False`` configura el relé en el estado ``off`` inicialmente (suponiendo configuración de activo bajo). .. code-block:: python # Initialize the relay connected to GPIO pin 17, starting in the 'off' state relay = OutputDevice(17, initial_value=False) #. Dentro del bloque ``try``, un bucle ``while True`` alterna continuamente el estado del relé. El relé se enciende y se apaga con una pausa de 1 segundo entre cada estado, acompañado de declaraciones de impresión en la consola. .. code-block:: python try: # Loop to continuously toggle the relay's state every second while True: print('Relay open...') # Inform that the relay is being activated relay.on() # Turn on the relay (assuming active low configuration) sleep(1) # Maintain the relay in the on state for 1 second print('...Relay close') # Inform that the relay is being deactivated relay.off() # Turn off the relay sleep(1) # Maintain the relay in the off state for 1 second #. Captura una interrupción del teclado (como Ctrl+C) para permitir la terminación del script de manera segura. El relé se apaga antes de salir del script. .. code-block:: python except KeyboardInterrupt: # Handle a keyboard interrupt (Ctrl+C) to exit the loop relay.off() # Ensure the relay is turned off before exiting pass