注釈
こんにちは、SunFounderのRaspberry Pi & Arduino & ESP32愛好家コミュニティへようこそ!Facebook上でRaspberry Pi、Arduino、ESP32についてもっと深く掘り下げ、他の愛好家と交流しましょう。
参加する理由は?
エキスパートサポート:コミュニティやチームの助けを借りて、販売後の問題や技術的な課題を解決します。
学び&共有:ヒントやチュートリアルを交換してスキルを向上させましょう。
独占的なプレビュー:新製品の発表や先行プレビューに早期アクセスしましょう。
特別割引:最新製品の独占割引をお楽しみください。
祭りのプロモーションとギフト:ギフトや祝日のプロモーションに参加しましょう。
👉 私たちと一緒に探索し、創造する準備はできていますか?[ここ]をクリックして今すぐ参加しましょう!
2.1.8 キーパッド¶
はじめに¶
キーパッドはボタンの長方形の配列です。このプロジェクトでは、 キーパッドを文字の入力に使用します。
必要な部品¶
このプロジェクトには、次のコンポーネントが必要です。
一式を購入するのが便利です、こちらがリンクです:
名前 |
このキットのアイテム |
リンク |
---|---|---|
Raphael Kit |
337 |
以下のリンクから別々に購入することもできます。
コンポーネントの紹介 |
購入リンク |
---|---|
- |
回路図¶
実験手順¶
ステップ 1: 回路を組み立てます。
ステップ 2: コードファイルを開きます。
cd ~/raphael-kit/python-pi5
ステップ 3: 実行します。
sudo python3 2.1.5_Keypad_zero.py
コードを実行すると、キーパッドのボタンの押下値(ボタンの値)が画面に表示されます。
コード
注釈
以下のコードを 変更/リセット/コピー/実行/停止 することができます。ただし、その前に raphael-kit/python_5
のソースコードパスに移動する必要があります。コードを変更した後、効果を確認するために直接実行できます。
#!/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
コードの説明
gpiozero
ライブラリからDigitalOutputDevice
およびButton
クラス、遅延のためのsleep
関数をインポートします。#!/usr/bin/env python3 from gpiozero import DigitalOutputDevice, Button from time import sleep
Keypad
クラスを定義します。__init__
メソッドは、指定された行と列のピンとキーパッドのキーレイアウトでキーパッドを初期化します。read
メソッドはキーパッドをスキャンし、押されたキーのリストを返します。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
GPIOピンの行と列を設定し、キーパッドのレイアウトを定義します。
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"]
指定された設定で
Keypad
クラスのインスタンスを作成します。try: ... # Create an instance of the Keypad class keypad = Keypad(rows_pins, cols_pins, keys) last_key_pressed = []
キーパッドを連続的に読み取り、キーの状態に変更があればそれを表示し、CPU負荷を軽減するために短い遅延を導入します。キーボード割り込み(Ctrl+Cなど)が発生した場合、スクリプトをきれいに終了するために処理します。
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