Raspberry Pi Keypad Relay

Hướng dẫn này sẽ chỉ bạn cách kết hợp keypad, relay và Raspberry Pi. Nếu người dùng nhập đúng mật khẩu trên keypad, Raspberry Pi sẽ bật relay.

Hướng dẫn cũng cung cấp mã Raspberry Pi để kích hoạt relay trong một khoảng thời gian nhất định và sau đó tắt nó. Hơn nữa, mã Raspberry Pi có khả năng xử lý nhiều mật khẩu.

Bằng cách kết nối relay với Raspberry Pi - Khóa Điện Từ (Electromagnetic Lock), Raspberry Pi - Solenoid Lock (Khóa Điện Từ), Raspberry Pi - Linear Actuator, Raspberry Pi - Điều Khiển Heating Element (Bộ Phận Gia Nhiệt), Raspberry Pi - Máy Bơm, hoặc Raspberry Pi - Quạt... Chúng ta có thể điều khiển chúng bằng keypad.

Raspberry Pi bàn phím ma trận rơ le

Phần Cứng Cần Thiết

1×Raspberry Pi 5
1×Bàn phím ma trận
1×Relay
1×dây jumper
1×(Khuyến nghị) Screw Terminal Block Shield for Raspberry Pi
1×(Khuyến nghị) Raspberry Pi Prototyping Base Plate & Breadboard Kit
1×(Khuyến nghị) HDMI Touch Screen Monitor for Raspberry Pi

Or you can buy the following kits:

1×DIYables Sensor Kit (30 sensors/displays)
1×DIYables Sensor Kit (18 sensors/displays)

Về Keypad và Relay

Nếu bạn chưa quen với keypad và relay (bao gồm sơ đồ chân, chức năng, lập trình, v.v.), các hướng dẫn sau có thể giúp bạn:

Sơ Đồ Đấu Nối

Raspberry Pi bàn phím ma trận rơ le sơ đồ đấu dây

This image is created using Fritzing. Click to enlarge image

Mã Raspberry Pi - bật relay nếu mật khẩu đúng

Các Bước Thực Hiện

  • Đảm bảo bạn đã cài đặt Raspbian hoặc hệ điều hành tương thích khác trên Raspberry Pi.
  • Đảm bảo Raspberry Pi của bạn được kết nối cùng mạng cục bộ với máy tính.
  • Đảm bảo Raspberry Pi của bạn được kết nối internet nếu cần cài đặt thư viện.
  • Nếu đây là lần đầu bạn sử dụng Raspberry Pi, hãy xem Raspberry Pi - Cài Đặt Phần Mềm
  • Kết nối máy tính với Raspberry Pi qua SSH sử dụng SSH client tích hợp trên Linux và macOS hoặc PuTTY trên Windows. Xem cách kết nối máy tính với Raspberry Pi qua SSH.
  • Đảm bảo bạn đã cài đặt thư viện RPi.GPIO. Nếu chưa, hãy cài đặt bằng lệnh sau:
sudo apt-get update sudo apt-get install python3-rpi.gpio
  • Tạo file script Python keypad_relay.py và thêm đoạn mã sau:
# Mã Raspberry Pi này được phát triển bởi newbiely.vn # Mã Raspberry Pi này được cung cấp để sử dụng công khai, không có ràng buộc. # Để xem hướng dẫn chi tiết và sơ đồ kết nối, vui lòng truy cập: # https://newbiely.vn/tutorials/raspberry-pi/raspberry-pi-keypad-relay import RPi.GPIO as GPIO import time # Define keypad layout KEYPAD = [ [1, 2, 3], [4, 5, 6], [7, 8, 9], ['*', 0, '#'] ] # Define GPIO pins for rows, columns, and relay ROW_PINS = [17, 27, 22, 24] COL_PINS = [25, 8, 7] RELAY_PIN = 16 # Adjust this to the actual GPIO pin connected to the relay # Password to unlock PASSWORD = [1, 2, 3, 4] # Initialize GPIO GPIO.setmode(GPIO.BCM) # Set up row pins as inputs with pull-up resistors for row_pin in ROW_PINS: GPIO.setup(row_pin, GPIO.IN, pull_up_down=GPIO.PUD_UP) # Set up column pins as outputs for col_pin in COL_PINS: GPIO.setup(col_pin, GPIO.OUT) GPIO.output(col_pin, GPIO.HIGH) # Set up relay pin as an output GPIO.setup(RELAY_PIN, GPIO.OUT) GPIO.output(RELAY_PIN, GPIO.LOW) # Initially, keep the relay off def get_key(): key = None # Scan each column for col_num, col_pin in enumerate(COL_PINS): GPIO.output(col_pin, GPIO.LOW) # Check each row for row_num, row_pin in enumerate(ROW_PINS): if GPIO.input(row_pin) == GPIO.LOW: key = KEYPAD[row_num][col_num] # Wait for key release while GPIO.input(row_pin) == GPIO.LOW: time.sleep(0.05) GPIO.output(col_pin, GPIO.HIGH) return key def check_password(input_password): return input_password == PASSWORD entered_keys = [] try: while True: pressed_key = get_key() if pressed_key is not None: print(f"Pressed: {pressed_key}") if pressed_key == '*': entered_keys = [] # reset the input password elif pressed_key == '#': if check_password(entered_keys): print("Password correct! Access granted.") GPIO.output(RELAY_PIN, GPIO.HIGH) # Activate the relay break else: print("Incorrect password. Try again.") entered_keys = [] # reset the input password else: entered_keys.append(pressed_key) time.sleep(0.1) except KeyboardInterrupt: GPIO.cleanup()
  • Lưu file và chạy script Python bằng cách thực thi lệnh sau trong terminal:
python3 keypad_relay.py
  • Nhập 9765 theo sau bởi phím #, sau đó 1234 theo sau bởi phím #.
  • Kiểm tra Terminal để xem kết quả và trạng thái của relay.
PuTTY - Raspberry Pi
The incorrect password! try again The correct password! Turning ON relay

Script chạy trong vòng lặp vô hạn liên tục cho đến khi bạn nhấn Ctrl + C trong terminal.

Giải Thích Mã

Các mật khẩu được ủy quyền được định nghĩa sẵn trong mã Raspberry Pi. Một chuỗi được sử dụng để lưu trữ mật khẩu mà người dùng nhập vào, gọi là chuỗi đầu vào. Trong keypad, hai phím (*#) được sử dụng cho mục đích đặc biệt: xóa mật khẩu và kết thúc mật khẩu. Khi một phím trên keypad được nhấn:

  • Nếu phím được nhấn không phải là hai phím đặc biệt, nó sẽ được thêm vào chuỗi đầu vào.
  • Nếu phím được nhấn là *, chuỗi đầu vào sẽ được xóa. Điều này có thể được sử dụng để bắt đầu hoặc bắt đầu lại việc nhập mật khẩu.
  • Nếu phím được nhấn là #:
    • Raspberry Pi sẽ kiểm tra xem chuỗi đầu vào có khớp với một trong những mật khẩu đã định nghĩa sẵn không, nếu có thì relay sẽ được bật.
    • Bất kể mật khẩu đúng hay sai, chuỗi đầu vào sẽ được xóa để chuẩn bị cho lần nhập tiếp theo.

Mã Raspberry Pi - bật relay trong một khoảng thời gian nếu mật khẩu đúng

Nếu mật khẩu đúng, relay sẽ được bật trong 5 giây. Sau khoảng thời gian đó, nó sẽ được tắt.

# Mã Raspberry Pi này được phát triển bởi newbiely.vn # Mã Raspberry Pi này được cung cấp để sử dụng công khai, không có ràng buộc. # Để xem hướng dẫn chi tiết và sơ đồ kết nối, vui lòng truy cập: # https://newbiely.vn/tutorials/raspberry-pi/raspberry-pi-keypad-relay import RPi.GPIO as GPIO import time # Define keypad layout KEYPAD = [ [1, 2, 3], [4, 5, 6], [7, 8, 9], ['*', 0, '#'] ] # Define GPIO pins for rows, columns, and relay ROW_PINS = [17, 27, 22, 24] COL_PINS = [25, 8, 7] RELAY_PIN = 16 # Adjust this to the actual GPIO pin connected to the relay # Password to unlock PASSWORD = [1, 2, 3, 4] # Initialize GPIO GPIO.setmode(GPIO.BCM) # Set up row pins as inputs with pull-up resistors for row_pin in ROW_PINS: GPIO.setup(row_pin, GPIO.IN, pull_up_down=GPIO.PUD_UP) # Set up column pins as outputs for col_pin in COL_PINS: GPIO.setup(col_pin, GPIO.OUT) GPIO.output(col_pin, GPIO.HIGH) # Set up relay pin as an output GPIO.setup(RELAY_PIN, GPIO.OUT) GPIO.output(RELAY_PIN, GPIO.LOW) # Initially, keep the relay off def get_key(): key = None # Scan each column for col_num, col_pin in enumerate(COL_PINS): GPIO.output(col_pin, GPIO.LOW) # Check each row for row_num, row_pin in enumerate(ROW_PINS): if GPIO.input(row_pin) == GPIO.LOW: key = KEYPAD[row_num][col_num] # Wait for key release while GPIO.input(row_pin) == GPIO.LOW: time.sleep(0.05) GPIO.output(col_pin, GPIO.HIGH) return key def check_password(input_password): return input_password == PASSWORD entered_keys = [] try: while True: pressed_key = get_key() if pressed_key is not None: print(f"Pressed: {pressed_key}") if pressed_key == '*': entered_keys = [] # reset the input password elif pressed_key == '#': if check_password(entered_keys): print("Password correct! Access granted.") GPIO.output(RELAY_PIN, GPIO.HIGH) # Activate the relay time.sleep(5) # Wait for 5 seconds GPIO.output(RELAY_PIN, GPIO.LOW) # Deactivate the relay break else: print("Incorrect password. Try again.") entered_keys = [] # reset the input password else: entered_keys.append(pressed_key) time.sleep(0.1) except KeyboardInterrupt: GPIO.cleanup()

Video Tutorial

Việc sản xuất video tốn rất nhiều thời gian. Nếu video hướng dẫn hữu ích cho việc học của bạn, hãy đăng ký kênh YouTube để ủng hộ. Nếu nhu cầu đủ cao, chúng tôi sẽ cố gắng làm thêm nhiều video.