.. note::

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

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

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

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

.. _2.1.8_py_pi5:

2.1.8 キーパッド
================

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

キーパッドはボタンの長方形の配列です。このプロジェクトでは、
キーパッドを文字の入力に使用します。

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

このプロジェクトには、次のコンポーネントが必要です。 

.. image:: ../python_pi5/img/2.1.8_keypad_list.png

一式を購入するのが便利です、こちらがリンクです： 

.. 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_keypad`
        - \-
        
回路図
-----------------

.. image:: ../python_pi5/img/2.1.8_keypad_chematic_1.png


.. image:: ../python_pi5/img/2.1.8_keypad_chematic_2.png


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

**ステップ 1:** 回路を組み立てます。

.. image:: ../python_pi5/img/2.1.8_keypad_circuit.png

**ステップ 2:** コードファイルを開きます。

.. raw:: html

   <run></run>

.. code-block:: 

    cd ~/raphael-kit/python-pi5

**ステップ 3:** 実行します。

.. raw:: html

   <run></run>

.. code-block:: 

    sudo python3 2.1.5_Keypad_zero.py

コードを実行すると、キーパッドのボタンの押下値（ボタンの値）が画面に表示されます。

.. warning::

    エラー メッセージ ``RuntimeError: Cannot determine SOC peripheral base address`` が表示された場合は、 :ref:`faq_soc` を参照してください。

**コード**

.. note::

    以下のコードを **変更/リセット/コピー/実行/停止** することができます。ただし、その前に ``raphael-kit/python_5`` のソースコードパスに移動する必要があります。コードを変更した後、効果を確認するために直接実行できます。


.. raw:: html

    <run></run>

.. code-block:: python

   #!/usr/bin/env python3
   from gpiozero import DigitalOutputDevice, Button
   from time import sleep

   class Keypad:
       def __init__(self, rows_pins, cols_pins, keys):
           """
           Initialize the Keypad with specified row and column pins and keypad layout.
           :param rows_pins: List of GPIO pins for the rows.
           :param cols_pins: List of GPIO pins for the columns.
           :param keys: List of keys in the keypad layout.
           """
           # Initialize row pins as DigitalOutputDevice
           self.rows = [DigitalOutputDevice(pin) for pin in rows_pins]
           # Initialize column pins as Buttons
           self.cols = [Button(pin, pull_up=False) for pin in cols_pins]
           self.keys = keys  # Set the keypad layout

       def read(self):
           """
           Read the currently pressed keys on the keypad.
           :return: A list of pressed keys.
           """
           pressed_keys = []
           # Scan each row and column to identify pressed keys
           for i, row in enumerate(self.rows):
               row.on()  # Enable the current row
               for j, col in enumerate(self.cols):
                   if col.is_pressed:  # Check if the column button is pressed
                       # Calculate the key index based on row and column
                       index = i * len(self.cols) + j
                       pressed_keys.append(self.keys[index])
               row.off()  # Disable the current row
           return pressed_keys

   try:
       # Configure rows, columns, and keypad layout
       rows_pins = [18, 23, 24, 25]
       cols_pins = [10, 22, 27, 17]
       keys = ["1", "2", "3", "A",
               "4", "5", "6", "B",
               "7", "8", "9", "C",
               "*", "0", "#", "D"]

       # Create an instance of the Keypad class
       keypad = Keypad(rows_pins, cols_pins, keys)
       last_key_pressed = []

       # Continuously read the keypad and print newly pressed keys
       while True:
           pressed_keys = keypad.read()
           if pressed_keys and pressed_keys != last_key_pressed:
               print(pressed_keys)  # Print the list of pressed keys
               last_key_pressed = pressed_keys
           sleep(0.1)  # Short delay to reduce CPU load

   except KeyboardInterrupt:
       # Handle a keyboard interrupt (Ctrl+C) for a clean exit
       pass



**コードの説明**

1. ``gpiozero`` ライブラリから ``DigitalOutputDevice`` および ``Button`` クラス、遅延のための ``sleep`` 関数をインポートします。

   .. code-block:: python

       #!/usr/bin/env python3
       from gpiozero import DigitalOutputDevice, Button
       from time import sleep

2. ``Keypad`` クラスを定義します。 ``__init__`` メソッドは、指定された行と列のピンとキーパッドのキーレイアウトでキーパッドを初期化します。 ``read`` メソッドはキーパッドをスキャンし、押されたキーのリストを返します。

   .. code-block:: python

       class Keypad:
           def __init__(self, rows_pins, cols_pins, keys):
               """
               Initialize the Keypad with specified row and column pins and keypad layout.
               :param rows_pins: List of GPIO pins for the rows.
               :param cols_pins: List of GPIO pins for the columns.
               :param keys: List of keys in the keypad layout.
               """
               # Initialize row pins as DigitalOutputDevice
               self.rows = [DigitalOutputDevice(pin) for pin in rows_pins]
               # Initialize column pins as Buttons
               self.cols = [Button(pin, pull_up=False) for pin in cols_pins]
               self.keys = keys  # Set the keypad layout

           def read(self):
               """
               Read the currently pressed keys on the keypad.
               :return: A list of pressed keys.
               """
               pressed_keys = []
               # Scan each row and column to identify pressed keys
               for i, row in enumerate(self.rows):
                   row.on()  # Enable the current row
                   for j, col in enumerate(self.cols):
                       if col.is_pressed:  # Check if the column button is pressed
                           # Calculate the key index based on row and column
                           index = i * len(self.cols) + j
                           pressed_keys.append(self.keys[index])
                   row.off()  # Disable the current row
               return pressed_keys

3. GPIOピンの行と列を設定し、キーパッドのレイアウトを定義します。

   .. code-block:: python

       try:
           # Configure rows, columns, and keypad layout
           rows_pins = [18, 23, 24, 25]
           cols_pins = [10, 22, 27, 17]
           keys = ["1", "2", "3", "A",
                   "4", "5", "6", "B",
                   "7", "8", "9", "C",
                   "*", "0", "#", "D"]

4. 指定された設定で ``Keypad`` クラスのインスタンスを作成します。

   .. code-block:: python

       try:
           ...

           # Create an instance of the Keypad class
           keypad = Keypad(rows_pins, cols_pins, keys)
           last_key_pressed = []

5. キーパッドを連続的に読み取り、キーの状態に変更があればそれを表示し、CPU負荷を軽減するために短い遅延を導入します。キーボード割り込み（Ctrl+Cなど）が発生した場合、スクリプトをきれいに終了するために処理します。

   .. code-block:: python

       try:
           ...

           # Continuously read the keypad and print newly pressed keys
           while True:
               pressed_keys = keypad.read()
               if pressed_keys and pressed_keys != last_key_pressed:
                   print(pressed_keys)  # Print the list of pressed keys
                   last_key_pressed = pressed_keys
               sleep(0.1)  # Short delay to reduce CPU load

       except KeyboardInterrupt:
           # Handle a keyboard interrupt (Ctrl+C) for a clean exit
           pass
