.. note::
Bonjour et bienvenue dans la Communauté Facebook des passionnés de Raspberry Pi, Arduino et ESP32 de SunFounder ! Plongez plus profondément dans l'univers des Raspberry Pi, Arduino et ESP32 avec d'autres passionnés.
**Pourquoi rejoindre ?**
- **Support d'experts** : Résolvez les problèmes après-vente et les défis techniques avec l'aide de notre communauté et de notre équipe.
- **Apprendre et partager** : Échangez des astuces et des tutoriels pour améliorer vos compétences.
- **Aperçus exclusifs** : Accédez en avant-première aux annonces de nouveaux produits et aux aperçus.
- **Réductions spéciales** : Profitez de réductions exclusives sur nos produits les plus récents.
- **Promotions festives et cadeaux** : Participez à des cadeaux et des promotions de vacances.
👉 Prêt à explorer et à créer avec nous ? Cliquez [|link_sf_facebook|] et rejoignez-nous aujourd'hui !
.. _2.1.8_py_pi5:
2.1.8 Clavier
================
Introduction
----------------
Un clavier est un ensemble rectangulaire de boutons. Dans ce projet, nous l'utiliserons pour entrer des caractères.
Composants nécessaires
------------------------------
Dans ce projet, nous avons besoin des composants suivants.
.. image:: ../python_pi5/img/2.1.8_keypad_list.png
Il est certainement pratique d'acheter un kit complet, voici le lien :
.. list-table::
:widths: 20 20 20
:header-rows: 1
* - Nom
- ARTICLES DANS CE KIT
- LIEN
* - Kit Raphael
- 337
- |link_Raphael_kit|
Vous pouvez également les acheter séparément via les liens ci-dessous.
.. list-table::
:widths: 30 20
:header-rows: 1
* - INTRODUCTION DU COMPOSANT
- LIEN D'ACHAT
* - :ref:`cpn_gpio_extension_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`
- \-
Schéma
-----------
.. image:: ../python_pi5/img/2.1.8_keypad_chematic_1.png
.. image:: ../python_pi5/img/2.1.8_keypad_chematic_2.png
Procédures expérimentales
------------------------------
**Étape 1 :** Construisez le circuit.
.. image:: ../python_pi5/img/2.1.8_keypad_circuit.png
**Étape 2 :** Ouvrez le fichier de code.
.. raw:: html
.. code-block::
cd ~/raphael-kit/python-pi5
**Étape 3 :** Exécutez.
.. raw:: html
.. code-block::
sudo python3 2.1.8_Keypad_zero.py
Après l'exécution du code, les valeurs des boutons pressés sur le clavier
(valeur des boutons) seront affichées à l'écran.
.. warning::
Si vous recevez le message d'erreur ``RuntimeError: Cannot determine SOC peripheral base address``, veuillez consulter :ref:`faq_soc`
**Code**
.. note::
Vous pouvez **Modifier/Réinitialiser/Copier/Exécuter/Arrêter** le code ci-dessous. Mais avant cela, vous devez vous rendre au chemin du code source comme ``raphael-kit/python-pi5``. Après avoir modifié le code, vous pouvez l'exécuter directement pour voir l'effet.
.. raw:: html
.. 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
**Explication du code**
#. Importe les classes ``DigitalOutputDevice`` et ``Button`` de la bibliothèque ``gpiozero``, ainsi que la fonction ``sleep`` pour les délais.
.. code-block:: python
#!/usr/bin/env python3
from gpiozero import DigitalOutputDevice, Button
from time import sleep
#. Définit la classe ``Keypad``. La méthode ``__init__`` initialise le clavier avec les broches de lignes et de colonnes spécifiées et les touches. La méthode ``read`` scanne le clavier et renvoie une liste des touches pressées.
.. 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
#. Configure les broches GPIO pour les lignes et les colonnes et définit la disposition du clavier.
.. 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"]
#. Crée une instance de la classe ``Keypad`` avec la configuration spécifiée.
.. code-block:: python
try:
...
# Create an instance of the Keypad class
keypad = Keypad(rows_pins, cols_pins, keys)
last_key_pressed = []
#. Lit continuellement le clavier pour les touches pressées, imprime les changements d'état des touches et introduit un court délai pour réduire la charge du CPU. Intercepte un KeyboardInterrupt (comme Ctrl+C) pour permettre une sortie propre du script.
.. 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