Search code examples
pythonlistlist-comprehensionkeypresskeypad

Check digit code after keypress using a keypad in Python


My goal is checkin if a digit code e.g.1234# is wrong or correct (using a keypad like this)

So my plan was to enumerate() items inside the list given by keypress, extract each value from the list using element index and finally validate the code. The problem is in the keypress function of the library because it always gives a list where all the values have the same index (0)

How can I achieve this? Maybe using list comprehension?

Here's the code:

#!/usr/bin/python3

import time
import digitalio
import board
import adafruit_matrixkeypad

 
# 3x4 matrix keypad on Raspberry Pi -
# rows and columns are mixed up 
cols = [digitalio.DigitalInOut(x) for x in (board.D13, board.D5, board.D26)]
rows = [digitalio.DigitalInOut(x) for x in (board.D6, board.D21, board.D20, board.D19)]
 
keys = ((1, 2, 3), (4, 5, 6), (7, 8, 9), ("*", 0, "#"))
 
keypad = adafruit_matrixkeypad.Matrix_Keypad(rows, cols, keys)


while True:
    keypressed = keypad.pressed_keys
    if keypressed:
        indices = [i for i, x in enumerate(keypressed)]
        print(indices, keypressed)
    time.sleep(0.3)
    

It returns:

root@rpi:~# python3 keypad.py
[0] [1]
[0] [2]
[0] [3]
[0] [4]
[0] [5]
[0] [6]
[0] [7]
[0] [8]
[0] [9]
[0] ['*']
[0] [0]
[0] ['#']

Solution

  • keypress is a one-item list, with key's value. If you try to enumerate over it, you will get only one item, on index 0.

    If you want to get all code, you need to store clicked keys, e.g.:

    key_log = ''
    while True:
        keypressed = keypad.pressed_keys
        if keypressed:
            key_log += str(keypressed[0])
        time.sleep(0.3)
    

    This will store all clicked keys in one string. If you want to check if code is correct, you can use:

    if '1234#' in key_log:
        key_log = '' # clear log
        # make action
    

    or:

    if '1234#' == key_log[-5:]:
        key_log = '' # clear log
        # make action
    

    So the whole code would look like this:

    code1 = '1234#'
    code2 = '568*2'
    key_log = ''
    
    while True:
        keypressed = keypad.pressed_keys
        if keypressed:
            key_log += str(keypressed[0])
    
            if key_log[-len(code1):] == code1:
                key_log = '' # clear log
                # make action1
    
            if key_log[-len(code2):] == code2:
                key_log = '' # clear log
                # make action2
    
        time.sleep(0.3)