.. note::

    ¡Hola! Bienvenido a la Comunidad de Entusiastas de SunFounder para Raspberry Pi, Arduino y ESP32 en Facebook. Profundiza en 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.
    - **Vistas exclusivas**: Obtén acceso temprano a nuevos anuncios de productos y adelantos.
    - **Descuentos especiales**: Disfruta de descuentos exclusivos en nuestros productos más nuevos.
    - **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 mismo!

.. _2.2.4_c:

2.2.4 Módulo de Interruptor de Lengüeta
============================================

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

En este proyecto, aprenderemos sobre el interruptor de lengüeta, que es un interruptor eléctrico que opera mediante un campo magnético aplicado.

.. image:: ../img/2.2.4reed_switch.png
    :width: 300
    :align: center

Componentes Necesarios
---------------------------------

En este proyecto, necesitamos los siguientes componentes.

.. image:: ../img/2.2.4component.png
    :width: 700
    :align: center

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

.. 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_resistor`
        - |link_resistor_buy|
    *   - :ref:`cpn_led`
        - |link_led_buy|
    *   - :ref:`cpn_reed_switch`
        - |link_reed_switch_buy|

Diagrama Esquemático
--------------------------

==================== ========== ======== ===
Nombre de la T-Board Pin físico wiringPi BCM
GPIO17               Pin 11     0        17
GPIO27               Pin 13     2        27
GPIO22               Pin 15     3        22
==================== ========== ======== ===

.. image:: ../img/reed_schematic.png
    :width: 400
    :align: center

.. image:: ../img/reed_schematic2.png
    :width: 400
    :align: center

Procedimientos Experimentales
-----------------------------------

**Paso 1:** Construir el circuito.

.. image:: ../img/2.2.4fritzing.png
    :width: 700
    :align: center

**Paso 2:** Cambiar de directorio.

.. raw:: html

   <run></run>

.. code-block::

    cd ~/raphael-kit/c/2.2.4/

**Paso 3:** Compilar.

.. raw:: html

   <run></run>

.. code-block::

    gcc 2.2.4_ReedSwitch.c -lwiringPi

**Paso 4:** Ejecutar.

.. raw:: html

   <run></run>

.. code-block::

    sudo ./a.out

El LED verde se encenderá cuando el código se ejecute. Si se coloca un imán cerca del módulo de interruptor de lengüeta, el LED rojo se enciende; al retirar el imán, el LED verde se enciende nuevamente.

.. note::

    Si no funciona después de ejecutar el código, o aparece un mensaje de error: \"wiringPi.h: No such file or directory\", consulte :ref:`install_wiringpi`.

**Código**

.. code-block:: c

    #include <wiringPi.h>
    #include <stdio.h>

    #define ReedPin		0
    #define Gpin		2
    #define Rpin		3

    void LED(char* color)
    {
        pinMode(Gpin, OUTPUT);
        pinMode(Rpin, OUTPUT);
        if (color == "RED")
        {
            digitalWrite(Rpin, HIGH);
            digitalWrite(Gpin, LOW);
        }
        else if (color == "GREEN")
        {
            digitalWrite(Rpin, LOW);
            digitalWrite(Gpin, HIGH);
        }
        else
            printf("LED Error");
    }

    int main(void)
    {
        if(wiringPiSetup() == -1){ //when initialize wiring failed,print messageto screen
            printf("setup wiringPi failed !");
            return 1; 
        }

        pinMode(ReedPin, INPUT);
        LED("GREEN");
        
        while(1){
            if(0 == digitalRead(ReedPin)){
                delay(10);
                if(0 == digitalRead(ReedPin)){
                    LED("RED");    
                    printf("Detected Magnetic Material!\n");    
                }
            }
            else if(1 == digitalRead(ReedPin)){
                delay(10);
                if(1 == digitalRead(ReedPin)){
                    while(!digitalRead(ReedPin));
                    LED("GREEN");
                }
            }
        }
        return 0;
    }

**Explicación del Código**

.. code-block:: c

    #define ReedPin		0
    #define Gpin		2
    #define Rpin		3

Los pines GPIO17, GPIO27 y GPIO22 de la T_Extension Board corresponden a los GPIO0, 
GPIO2 y GPIO3 en wiringPi. Asigna GPIO0, GPIO2 y GPIO3 a ``ReedPin``, ``Gpin`` y ``Rpin``.

.. code-block:: c

    void LED(char* color)
    {
        pinMode(Gpin, OUTPUT);
        pinMode(Rpin, OUTPUT);
        if (color == "RED")
        {
            digitalWrite(Rpin, HIGH);
            digitalWrite(Gpin, LOW);
        }
        else if (color == "GREEN")
        {
            digitalWrite(Rpin, LOW);
            digitalWrite(Gpin, HIGH);
        }
        else
            printf("LED Error");
    }

Establece una función ``LED()`` para controlar los 2 LEDs, el parámetro de esta función es ``color``.

Cuando ``color`` es ``"RED"``, establece ``Rpin`` en ``HIGH`` (enciende el LED rojo) y ``Gpin`` en ``LOW`` (apaga el LED verde); cuando ``color`` es ``"GREEN"``, enciende el LED verde y apaga el LED rojo.

.. code-block:: c

    while(1){
            if(0 == digitalRead(ReedPin)){
                delay(10);
                if(0 == digitalRead(ReedPin)){
                    LED("RED");    
                    printf("Detected Magnetic Material!\n");    
                }
            }
            else if(1 == digitalRead(ReedPin)){
                delay(10);
                if(1 == digitalRead(ReedPin)){
                    while(!digitalRead(ReedPin));
                    LED("GREEN");
                }
            }
        }

Lee el valor del módulo de interruptor de lengüeta, si el valor leído 2 veces es 0, llama a ``LED("RED")`` para encender el LED rojo y muestra el mensaje ``"Magnetic material detected!"``.

Si el valor es 1, se enciende el LED verde.

Imagen del Fenómeno
------------------------

.. image:: ../img/2.2.4reed_switch.JPG
    :width: 500
    :align: center