.. note::

    こんにちは、SunFounderのRaspberry Pi & Arduino & ESP32愛好家コミュニティへようこそ！Facebook上でRaspberry Pi、Arduino、ESP32についてもっと深く掘り下げ、他の愛好家と交流しましょう。

    **参加する理由は？**

    - **エキスパートサポート**：コミュニティやチームの助けを借りて、販売後の問題や技術的な課題を解決します。
    - **学び＆共有**：ヒントやチュートリアルを交換してスキルを向上させましょう。
    - **独占的なプレビュー**：新製品の発表や先行プレビューに早期アクセスしましょう。
    - **特別割引**：最新製品の独占割引をお楽しみください。
    - **祭りのプロモーションとギフト**：ギフトや祝日のプロモーションに参加しましょう。

    👉 私たちと一緒に探索し、創造する準備はできていますか？[|link_sf_facebook|]をクリックして今すぐ参加しましょう！

.. _2.2.4_py:

2.2.4 リードスイッチモジュール
==============================

はじめに
-------------------

このプロジェクトでは、磁場が作用することで動作する電気スイッチであるリードスイッチについて学びます。

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

必要な部品
------------------------------

このプロジェクトで必要なコンポーネントは以下の通りです。

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

一式をまとめて購入すると確実に便利です。リンクはこちら：

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

    *   - 名前	
        - このキットのアイテム
        - リンク
    *   - Raphael Kit
        - 337
        - |link_Raphael_kit|

以下のリンクから個別に購入することもできます。

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

    *   - コンポーネントの紹介
        - 購入リンク

    *   - :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_reed_switch`
        - |link_reed_switch_buy|

回路図
-----------------------

============ ======== ======== ===
T-Board Name physical wiringPi BCM
GPIO17       ピン11     0          17
GPIO27       ピン13     2          27
GPIO22       ピン15     3          22
============ ======== ======== ===

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

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

実験手順
-------------------------------

**ステップ1:** 回路を組む。

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

**ステップ2:** ディレクトリを変更する。

.. raw:: html

   <run></run>

.. code-block::

    cd ~/raphael-kit/python/

**ステップ3:** 実行する。

.. raw:: html

   <run></run>

.. code-block::

    sudo python3 2.2.4_ReedSwitch.py

コードが実行されると、緑のLEDが点灯します。リードスイッチモジュールに磁石を近づけると、赤いLEDが点灯します。磁石を離すと、緑のLEDが再び点灯します。

**コード**

.. note::

    下記のコードは **変更/リセット/コピー/実行/停止** が可能です。ただし、事前にソースコードのパス、例えば ``raphael-kit/python`` に移動する必要があります。コードを修正した後、その効果を直接確認することができます。

.. raw:: html

    <run></run>

.. code-block:: python

    #!/usr/bin/env python3
    import RPi.GPIO as GPIO
    import time

    ReedPin = 17
    Gpin    = 27
    Rpin    = 22

    def setup():
        GPIO.setmode(GPIO.BCM)       # 
        GPIO.setup(Gpin, GPIO.OUT)     # Set Green Led Pin mode to output
        GPIO.setup(Rpin, GPIO.OUT)     # Set Red Led Pin mode to output
        GPIO.setup(ReedPin, GPIO.IN, pull_up_down=GPIO.PUD_UP)    # Set ReedPin's mode is input, and pull up to high level(3.3V)
        GPIO.add_event_detect(ReedPin, GPIO.BOTH, callback=detect, bouncetime=200)

    def Led(x):
        if x == 0:
            GPIO.output(Rpin, 1)
            GPIO.output(Gpin, 0)
        if x == 1:
            GPIO.output(Rpin, 0)
            GPIO.output(Gpin, 1)

    def detect(self):
        Led(GPIO.input(ReedPin))

    def loop():
        while True:
            pass

    def destroy():
        GPIO.output(Gpin, GPIO.HIGH)       # Green led on
        GPIO.output(Rpin, GPIO.LOW)       # Red led off
        GPIO.cleanup()                     # Release resource

    if __name__ == '__main__':     # Program start from here
        setup()
        detect()
        try:
            loop()
        except KeyboardInterrupt:  # When 'Ctrl+C' is pressed, the child program destroy() will be  executed.
            destroy()

**コードの説明**

.. code-block:: python

    ReedPin = 17
    Gpin    = 27
    Rpin    = 22

    def setup():
        GPIO.setmode(GPIO.BCM)       # 
        GPIO.setup(Gpin, GPIO.OUT)     # Set Green Led Pin mode to output
        GPIO.setup(Rpin, GPIO.OUT)     # Set Red Led Pin mode to output
        GPIO.setup(ReedPin, GPIO.IN, pull_up_down=GPIO.PUD_UP)    # Set ReedPin's mode is input, and pull up to high level(3.3V)
        GPIO.add_event_detect(ReedPin, GPIO.BOTH, callback=detect, bouncetime=200)

GPIOモードをBCMナンバリングに設定します。 ``ReedPin`` 、 ``Gpin`` 、 ``Rpin`` は、それぞれGPIO17、GPIO27、GPIO22に接続されています。

``GPIO.add_event_detect()`` は、 ``ReedPin`` の値（レベル）が変更された際にトリガーされるイベントを追加するために使用されます。この際、コールバック関数 ``detect()`` が呼び出されます。

.. code-block:: python

    def Led(x):
        if x == 0:
            GPIO.output(Rpin, 1)
            GPIO.output(Gpin, 0)
        if x == 1:
            GPIO.output(Rpin, 0)
            GPIO.output(Gpin, 1)

``Led()`` という関数を定義して、2つのLEDをオンまたはオフにします。 ``x=0`` の場合、赤いLEDが点灯します。それ以外の場合、緑のLEDが点灯します。

.. code-block:: python

    def detect(self):
    Led(GPIO.input(ReedPin))

このコールバック関数では、リードスイッチの値を用いて2つのLEDを制御します。

現象の画像
------------------------

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