Bemerkung

Hallo und willkommen in der SunFounder Raspberry Pi & Arduino & ESP32 Enthusiasten-Gemeinschaft auf Facebook! Tauchen Sie tiefer ein in die Welt von Raspberry Pi, Arduino und ESP32 mit anderen Enthusiasten.

Warum beitreten?

  • Expertenunterstützung: Lösen Sie Nachverkaufsprobleme und technische Herausforderungen mit Hilfe unserer Gemeinschaft und unseres Teams.

  • Lernen & Teilen: Tauschen Sie Tipps und Anleitungen aus, um Ihre Fähigkeiten zu verbessern.

  • Exklusive Vorschauen: Erhalten Sie frühzeitigen Zugang zu neuen Produktankündigungen und exklusiven Einblicken.

  • Spezialrabatte: Genießen Sie exklusive Rabatte auf unsere neuesten Produkte.

  • Festliche Aktionen und Gewinnspiele: Nehmen Sie an Gewinnspielen und Feiertagsaktionen teil.

👉 Sind Sie bereit, mit uns zu erkunden und zu erschaffen? Klicken Sie auf [hier] und treten Sie heute bei!

4.1.11 Passwortschloss

Einführung

In diesem Projekt verwenden wir ein Tastenfeld und ein LCD, um ein Kombinationsschloss zu erstellen. Das LCD zeigt eine entsprechende Aufforderung an, um Ihr Passwort auf dem Tastenfeld einzugeben. Wenn das Passwort korrekt eingegeben wird, wird „Korrekt“ angezeigt.

Auf Basis dieses Projekts können wir zusätzliche elektronische Komponenten hinzufügen, wie z.B. einen Summer, LEDs und so weiter, um verschiedene experimentelle Phänomene bei der Passworteingabe hinzuzufügen.

Benötigte Komponenten

Für dieses Projekt benötigen wir die folgenden Komponenten.

../_images/4.1.14_password_lock_list.png

Es ist definitiv praktisch, ein ganzes Kit zu kaufen, hier ist der Link:

Name

ARTIKEL IN DIESEM KIT

LINK

Raphael Kit

337

Raphael Kit

Sie können sie auch separat über die untenstehenden Links kaufen.

KOMPONENTENVORSTELLUNG

KAUF-LINK

GPIO-Erweiterungsplatine

BUY

Steckbrett

BUY

Jumper-Kabel

BUY

Widerstand

BUY

I2C LCD1602

BUY

Tastenfeld

-

Schaltplan

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

../_images/4.1.14_password_lock_schematic.png

Experimentelle Verfahren

Schritt 1: Bauen Sie den Schaltkreis.

../_images/4.1.14_password_lock_circuit.png

Schritt 2: Verzeichnis wechseln.

cd ~/raphael-kit/python-pi5

Schritt 3: Ausführen.

sudo python3 4.1.14_PasswordLock_zero.py

Nachdem der Code ausgeführt wurde, wird das Tastenfeld verwendet, um das Passwort: 1984 einzugeben. Wenn auf dem LCD1602 „CORRECT“ erscheint, ist das Passwort korrekt; andernfalls wird „WRONG KEY“ angezeigt.

Bemerkung

  • Wenn Sie den Fehler FileNotFoundError: [Errno 2] No such file or directory: '/dev/i2c-1' erhalten, müssen Sie I2C Konfiguration zu Rate ziehen, um das I2C zu aktivieren.

  • Wenn der Fehler ModuleNotFoundError: No module named 'smbus2' auftritt, führen Sie bitte sudo pip3 install smbus2 aus.

  • Wenn der Fehler OSError: [Errno 121] Remote I/O error erscheint, bedeutet das, dass das Modul falsch verdrahtet ist oder das Modul defekt ist.

  • Wenn der Code und die Verdrahtung in Ordnung sind, aber das LCD immer noch keinen Inhalt anzeigt, können Sie das Potentiometer auf der Rückseite drehen, um den Kontrast zu erhöhen.

Code

Bemerkung

Sie können den untenstehenden Code Modifizieren/Zurücksetzen/Kopieren/Ausführen/Stoppen. Aber davor müssen Sie zum Quellcodepfad wie raphael-kit/python-pi5 gehen. Nachdem Sie den Code modifiziert haben, können Sie ihn direkt ausführen, um den Effekt zu sehen.

#!/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

Code-Erklärung

  1. Dieser Abschnitt importiert die notwendigen Bibliotheken für das Projekt. LCD1602 wird für das LCD-Display verwendet, gpiozero stellt Klassen für LED, Buzzer und Button zur Verfügung, ADC0834 ist für die Analog-Digital-Umwandlung, und time sowie math sind Python-Standardbibliotheken für zeitbezogene Funktionen und mathematische Operationen.

    #!/usr/bin/env python3
    
    import LCD1602
    from gpiozero import LED, Buzzer, Button
    import ADC0834
    import time
    import math
    
  2. Definiert eine benutzerdefinierte Klasse für die Verwaltung des Keypads. Sie initialisiert das Keypad mit spezifischen Zeilen- und Spaltenpins und bietet eine read Methode, um gedrückte Tasten zu erkennen.

    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
    
  3. Richtet das Passwortüberprüfungssystem ein. LENS definiert die Länge des Passworts. password ist das voreingestellte korrekte Passwort, während testword verwendet wird, um die Eingabe des Benutzers zu speichern. keyIndex verfolgt die aktuelle Position in der Eingabe des Benutzers.

    # 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
    
  4. Funktion zum Vergleichen des eingegebenen Passworts (testword) mit dem voreingestellten Passwort (password) und Rückgabe des Ergebnisses.

    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
    
  5. Initialisiert das Keypad und das LCD-Display. Zeigt eine Willkommensnachricht und Anweisungen zur Passworteingabe an.

    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)
    
  6. Die Hauptschleife für die Verarbeitung der Keypadeingabe und die Passwortüberprüfung. Sie aktualisiert das LCD-Display basierend auf dem eingegebenen Passwort und gibt Feedback, ob das Passwort korrekt oder falsch ist.

    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)
    
  7. Führt die Einrichtung durch und tritt in die Hauptschleife ein. Ermöglicht einen sauberen Ausstieg aus dem Programm mittels Tastaturunterbrechung (Ctrl+C), wobei das LCD-Display gelöscht wird.

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