.. note::
こんにちは、SunFounderのRaspberry Pi & Arduino & ESP32愛好家コミュニティへようこそ!Facebook上でRaspberry Pi、Arduino、ESP32についてもっと深く掘り下げ、他の愛好家と交流しましょう。
**参加する理由は?**
- **エキスパートサポート**:コミュニティやチームの助けを借りて、販売後の問題や技術的な課題を解決します。
- **学び&共有**:ヒントやチュートリアルを交換してスキルを向上させましょう。
- **独占的なプレビュー**:新製品の発表や先行プレビューに早期アクセスしましょう。
- **特別割引**:最新製品の独占割引をお楽しみください。
- **祭りのプロモーションとギフト**:ギフトや祝日のプロモーションに参加しましょう。
👉 私たちと一緒に探索し、創造する準備はできていますか?[|link_sf_facebook|]をクリックして今すぐ参加しましょう!
.. _4.1.14_py:
4.1.14 パスワードロック
================================
はじめに
-------------
このプロジェクトでは、キーパッドとLCDを使用して、組み合わせロックを作成します。LCDには、キーパッドでパスワードを入力するように促す対応するプロンプトが表示されます。正しくパスワードが入力された場合、「正解」と表示されます。
このプロジェクトを基にして、ブザーやLEDなどの追加の電子部品を追加することで、パスワード入力の異なる実験現象を追加できます。
必要な部品
------------------------------
このプロジェクトでは、以下のコンポーネントが必要です。
.. image:: ../img/list_Password_Lock.png
: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:: ../img/Schematic_three_one9.png
:align: center
実験手順
-------------------------
**ステップ1:** 回路を組み立てる。
.. image:: ../img/image262.png
**ステップ2:** ディレクトリを変更する。
.. raw:: html
.. code-block::
cd ~/raphael-kit/python/
**ステップ3:** 実行する。
.. raw:: html
.. code-block::
sudo python3 4.1.14_PasswordLock.py
コードが実行されると、キーパッドはパスワードを入力するために使用されます:1984。LCD1602に「正解」が表示される場合、パスワードに問題はありません。それ以外の場合、「間違ったキー」と表示されます。
.. note::
* エラー ``FileNotFoundError: [Errno 2] No such file or directory: '/dev/i2c-1'`` が表示された場合、 :ref:`i2c_config` を参照してI2Cを有効にする必要があります。
* エラー ``ModuleNotFoundError: No module named 'smbus2'`` が表示される場合、 ``sudo apt install python3-smbus2`` を実行してください。
* エラー ``OSError: [Errno 121] Remote I/O error`` が表示される場合、モジュールが誤って配線されているか、モジュールが壊れている可能性があります。
* コードと配線が正しいにも関わらず、LCDに内容が表示されない場合、背面のポテンショメータを回してコントラストを上げることができます。
**コード**
.. note::
以下のコードを **変更/リセット/コピー/実行/停止** することができます。しかし、それを行う前に、ソースコードのパス ``raphael-kit/python`` に移動する必要があります。コードを修正した後、その効果を直接確認するために実行できます。
.. raw:: html
.. code-block:: python
#!/usr/bin/env python3
import RPi.GPIO as GPIO
import time
import LCD1602
##################### HERE IS THE KEYPAD LIBRARY TRANSPLANTED FROM Arduino ############
#class Key:Define some of the properties of Key
class Keypad():
def __init__(self, rowsPins, colsPins, keys):
self.rowsPins = rowsPins
self.colsPins = colsPins
self.keys = keys
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BCM)
GPIO.setup(self.rowsPins, GPIO.OUT, initial=GPIO.LOW)
GPIO.setup(self.colsPins, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)
def read(self):
pressed_keys = []
for i, row in enumerate(self.rowsPins):
GPIO.output(row, GPIO.HIGH)
for j, col in enumerate(self.colsPins):
index = i * len(self.colsPins) + j
if (GPIO.input(col) == 1):
pressed_keys.append(self.keys[index])
GPIO.output(row, GPIO.LOW)
return pressed_keys
################ EXAMPLE CODE START HERE ################
LENS = 4
password=['1','9','8','4']
testword=['0','0','0','0']
keyIndex=0
def check():
for i in range(0,LENS):
if(password[i]!=testword[i]):
return 0
return 1
def setup():
global keypad, last_key_pressed
rowsPins = [18,23,24,25]
colsPins = [10,22,27,17]
keys = ["1","2","3","A",
"4","5","6","B",
"7","8","9","C",
"*","0","#","D"]
keypad = Keypad(rowsPins, colsPins, keys)
last_key_pressed = []
LCD1602.init(0x27, 1) # init(slave address, background light)
LCD1602.clear()
LCD1602.write(0, 0, 'WELCOME!')
LCD1602.write(2, 1, 'Enter password')
time.sleep(2)
def destroy():
LCD1602.clear()
GPIO.cleanup()
def loop():
global keyIndex
global LENS
global keypad, last_key_pressed
while(True):
pressed_keys = keypad.read()
if len(pressed_keys) != 0 and last_key_pressed != pressed_keys:
LCD1602.clear()
LCD1602.write(0, 0, "Enter password:")
LCD1602.write(15-keyIndex,1, pressed_keys)
testword[keyIndex]=pressed_keys
keyIndex+=1
if (keyIndex is LENS):
if (check() is 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=keyIndex%LENS
last_key_pressed = pressed_keys
time.sleep(0.1)
if __name__ == '__main__': # Program start from here
try:
setup()
loop()
except KeyboardInterrupt: # When 'Ctrl+C' is pressed, the program destroy() will be executed.
destroy()
**コード説明**
.. code-block:: python
LENS = 4
password=['1','9','8','4']
...
rowsPins = [18,23,24,25]
colsPins = [10,22,27,17]
keys = ["1","2","3","A",
"4","5","6","B",
"7","8","9","C",
"*","0","#","D"]
ここでは、パスワードの長さLENS、マトリックスキーボードのキーを保存する配列keys、および正しいパスワードを保存する配列passwordを定義します。
.. code-block:: python
class Keypad():
def __init__(self, rowsPins, colsPins, keys):
self.rowsPins = rowsPins
self.colsPins = colsPins
self.keys = keys
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BCM)
GPIO.setup(self.rowsPins, GPIO.OUT, initial=GPIO.LOW)
GPIO.setup(self.colsPins, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)
...
このクラスは、押されたキーの値を読み取るコードです。詳細については、この文書の :ref:`2.1.8_py` を参照してください。
.. code-block:: python
while(True):
pressed_keys = keypad.read()
if len(pressed_keys) != 0 and last_key_pressed != pressed_keys:
LCD1602.clear()
LCD1602.write(0, 0, "Enter password:")
LCD1602.write(15-keyIndex,1, pressed_keys)
testword[keyIndex]=pressed_keys
keyIndex+=1
...
キーの値を読み取り、テスト配列testwordに保存します。保存されたキーの値が4を超える場合、パスワードの正確性が自動的に確認され、確認結果がLCDインターフェースに表示されます。
.. code-block:: python
def check():
for i in range(0,LENS):
if(password[i]!=testword[i]):
return 0
return 1
パスワードの正確性を確認します。パスワードが正しく入力されている場合は1を返し、そうでない場合は0を返します。
現象の画像
---------------------
.. image:: ../img/image263.jpeg
:align: center