.. note::

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

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

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

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

.. _4.1.14_py_pi5:

4.1.11 パスワードロック
================================

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

このプロジェクトでは、キーパッドとLCDを使用して組み合わせ錠を作成します。LCDには、キーパッドにパスワードを入力するための対応するプロンプトが表示されます。パスワードが正しく入力されると、「正しい」と表示されます。

このプロジェクトを基に、ブザーやLEDなどの追加の電子コンポーネントを追加して、パスワードの入力に異なる実験現象を追加することができます。

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

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

.. image:: ../python_pi5/img/4.1.14_password_lock_list.png
    :width: 800
    :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_i2c_lcd`
        - |link_i2clcd1602_buy|
    *   - :ref:`cpn_keypad`
        - \-

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

============ ======== ======== ===
T-Board Name physical wiringPi BCM
GPIO18       Pin 12   1        18
GPIO23       Pin 16   4        23
GPIO24       Pin 18   5        24
GPIO25       Pin 22   6        25
GPIO17       Pin 11   0        17
GPIO27       Pin 13   2        27
GPIO22       Pin 15   3        22
SPIMOSI      Pin 19   12       10
SDA1         Pin 3             
SCL1         Pin 5             
============ ======== ======== ===

.. image:: ../python_pi5/img/4.1.14_password_lock_schematic.png
   :align: center

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

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

.. image:: ../python_pi5/img/4.1.14_password_lock_circuit.png

**ステップ2：** ディレクトリを変更します。

.. raw:: html

   <run></run>

.. code-block:: 

    cd ~/raphael-kit/python-pi5

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

.. raw:: html

   <run></run>

.. code-block:: 

    sudo python3 3.1.9_PasswordLock_zero.py

コードが実行されると、キーパッドを使用してパスワード（1984）を入力します。LCD1602に「CORRECT」が表示された場合、パスワードは正しいです。それ以外の場合、「WRONG KEY」が表示されます。

.. note::

    * ``FileNotFoundError: [Errno 2] No such file or directory: '/dev/i2c-1'`` というエラーが表示される場合は、I2Cを有効にするために :ref:`i2c_config` を参照してください。
    * ``ModuleNotFoundError: No module named 'smbus2'`` エラーが表示される場合は、 ``sudo pip3 install smbus2`` を実行してください。
    * エラー ``OSError: [Errno 121] Remote I/O error`` が表示される場合、モジュールが配線されていないか、モジュールが壊れていることを意味します。
    * コードと配線が正常であるが、LCDに内容が表示されない場合、背面のポテンショメータを回してコントラストを上げることができます。


.. warning::

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

**コード**

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

.. raw:: html

    <run></run>

.. code-block:: python

   #!/usr/bin/env python3

   from gpiozero import DigitalOutputDevice, Button
   from time import sleep
   import LCD1602

   class Keypad:
       def __init__(self, rows_pins, cols_pins, keys):
           """
           Initialize the Keypad with specified row and column pins and keys.
           :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.
           """
           self.rows = [DigitalOutputDevice(pin) for pin in rows_pins]  # Row pins setup
           self.cols = [Button(pin, pull_up=False) for pin in cols_pins]  # Column pins setup
           self.keys = keys  # Keypad key layout

       def read(self):
           """
           Read and return a list of keys that are currently pressed.
           :return: List of pressed keys.
           """
           pressed_keys = []
           for i, row in enumerate(self.rows):
               row.on()  # Activate current row
               for j, col in enumerate(self.cols):
                   if col.is_pressed:
                       index = i * len(self.cols) + j
                       pressed_keys.append(self.keys[index])
               row.off()  # Deactivate row after checking
           return pressed_keys

   # Password verification setup
   LENS = 4
   password = ['1', '9', '8', '4']  # Preset password
   testword = ['0', '0', '0', '0']  # User input storage
   keyIndex = 0  # Index for input keys

   def check():
       """
       Check if the entered password matches the preset password.
       :return: 1 if match, 0 otherwise.
       """
       for i in range(LENS):
           if password[i] != testword[i]:
               return 0
       return 1

   def setup():
       """
       Setup the keypad and LCD display.
       """
       global keypad, last_key_pressed
       # Pin configuration for keypad
       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"]

       # Initialize keypad and LCD
       keypad = Keypad(rows_pins, cols_pins, keys)
       last_key_pressed = []
       LCD1602.init(0x27, 1)  # Initialize LCD
       LCD1602.clear()
       LCD1602.write(0, 0, 'WELCOME!')
       LCD1602.write(2, 1, 'Enter password')
       sleep(2)

   def loop():
       """
       Main loop for handling keypad input and password verification.
       """
       global keyIndex, LENS, keypad, last_key_pressed
       while True:
           pressed_keys = keypad.read()
           if pressed_keys and pressed_keys != last_key_pressed:
               if keyIndex < LENS:
                   LCD1602.clear()
                   LCD1602.write(0, 0, "Enter password:")
                   LCD1602.write(15 - keyIndex, 1, pressed_keys[0])
                   testword[keyIndex] = pressed_keys[0]
                   keyIndex += 1

               if keyIndex == LENS:
                   if check() == 0:
                       LCD1602.clear()
                       LCD1602.write(3, 0, "WRONG KEY!")
                       LCD1602.write(0, 1, "please try again")
                   else:
                       LCD1602.clear()
                       LCD1602.write(4, 0, "CORRECT!")
                       LCD1602.write(2, 1, "welcome back")
                   keyIndex = 0  # Reset key index after checking

           last_key_pressed = pressed_keys
           sleep(0.1)

   try:
       setup()
       loop()
   except KeyboardInterrupt:
       LCD1602.clear()  # Clear LCD display on interrupt

**コードの説明**

#. スクリプトはgpiozeroライブラリからデジタル出力デバイスとボタンの管理クラスをインポートします。また、timeモジュールからsleep関数をインポートし、スクリプトの実行中に遅延を追加します。さらに、LCD1602ライブラリもインポートして、LCD1602ディスプレイを制御します。

   .. code-block:: python

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

#. キーパッドを管理するためのカスタムクラスを定義します。指定された行と列のピンでキーパッドを初期化し、押されたキーを検出する ``read`` メソッドを提供します。

   .. code-block:: python

       class Keypad:
           def __init__(self, rows_pins, cols_pins, keys):
               """
               Initialize the Keypad with specified row and column pins and keys.
               :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.
               """
               self.rows = [DigitalOutputDevice(pin) for pin in rows_pins]  # Row pins setup
               self.cols = [Button(pin, pull_up=False) for pin in cols_pins]  # Column pins setup
               self.keys = keys  # Keypad key layout

           def read(self):
               """
               Read and return a list of keys that are currently pressed.
               :return: List of pressed keys.
               """
               pressed_keys = []
               for i, row in enumerate(self.rows):
                   row.on()  # Activate current row
                   for j, col in enumerate(self.cols):
                       if col.is_pressed:
                           index = i * len(self.cols) + j
                           pressed_keys.append(self.keys[index])
                   row.off()  # Deactivate row after checking
               return pressed_keys

#. パスワードの検証システムをセットアップします。 ``LENS`` はパスワードの長さを定義します。 ``password`` はプリセットの正しいパスワードで、 ``testword`` はユーザーの入力を保存するために使用されます。 ``keyIndex`` はユーザーの入力の現在位置を追跡します。

   .. code-block:: python

       # Password verification setup
       LENS = 4
       password = ['1', '9', '8', '4']  # Preset password
       testword = ['0', '0', '0', '0']  # User input storage
       keyIndex = 0  # Index for input keys

#. 入力されたパスワード（ ``testword`` ）とプリセットのパスワード（ ``password`` ）を比較し、結果を返す関数。

   .. code-block:: python

       def check():
           """
           Check if the entered password matches the preset password.
           :return: 1 if match, 0 otherwise.
           """
           for i in range(LENS):
               if password[i] != testword[i]:
                   return 0
           return 1

#. キーパッドとLCDディスプレイの初期化を行います。歓迎メッセージとパスワード入力の指示を表示します。

   .. code-block:: python

       def setup():
           """
           Setup the keypad and LCD display.
           """
           global keypad, last_key_pressed
           # Pin configuration for keypad
           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"]

           # Initialize keypad and LCD
           keypad = Keypad(rows_pins, cols_pins, keys)
           last_key_pressed = []
           LCD1602.init(0x27, 1)  # Initialize LCD
           LCD1602.clear()
           LCD1602.write(0, 0, 'WELCOME!')
           LCD1602.write(2, 1, 'Enter password')
           sleep(2)

#. キーパッド入力とパスワードの検証を処理するメインループです。入力されたパスワードに基づいてLCDディスプレイを更新し、パスワードが正しいかどうかに応じてフィードバックを提供します。

   .. code-block:: python

       def loop():
           """
           Main loop for handling keypad input and password verification.
           """
           global keyIndex, LENS, keypad, last_key_pressed
           while True:
               pressed_keys = keypad.read()
               if pressed_keys and pressed_keys != last_key_pressed:
                   if keyIndex < LENS:
                       LCD1602.clear()
                       LCD1602.write(0, 0, "Enter password:")
                       LCD1602.write(15 - keyIndex, 1, pressed_keys[0])
                       testword[keyIndex] = pressed_keys[0]
                       keyIndex += 1

                   if keyIndex == LENS:
                       if check() == 0:
                           LCD1602.clear()
                           LCD1602.write(3, 0, "WRONG KEY!")
                           LCD1602.write(0, 1, "please try again")
                       else:
                           LCD1602.clear()
                           LCD1602.write(4, 0, "CORRECT!")
                           LCD1602.write(2, 1, "welcome back")
                       keyIndex = 0  # Reset key index after checking

               last_key_pressed = pressed_keys
               sleep(0.1)

#. セットアップを実行し、メインループに入ります。キーボード割り込み（Ctrl+C）を使用してプログラムをクリーンに終了させることができます。LCD表示をクリアします。

   .. code-block:: python

       try:
           setup()
           loop()
       except KeyboardInterrupt:
           LCD1602.clear()  # Clear LCD display on interrupt

