I'm making a python script for a 4x4 keypad that's connected to a raspberry pi where the user enters a 4 pin code and the program tells the user whether or not it's correct. In order to take in the input from the keypad I'm using this python library called pad4pi(python 3 version) and it's almost done except for one part, I want to implement a timeout function so that if the user doesn't press any buttons on the keypad within a certain time frame(ie 5 seconds), the program resets the code variable which stores all the numbers the user enters from the keypad and starts over with the pin code entering process.

Here is the code:

from pad4pi import rpi_gpio
import time

# Setup Keypad

# same as calling: factory.create_4_by_4_keypad, still we put here fyi:
ROW_PINS = [11, 9, 0, 5] # BCM numbering
COL_PINS = [6, 13, 19, 26] # BCM numbering

factory = rpi_gpio.KeypadFactory()

keypad = factory.create_keypad(keypad=KEYPAD, row_pins=ROW_PINS, col_pins=COL_PINS)

code=""#the numbers that user enters will be appended to this variable
pin="0126"#this is the correct pin code, the code variable is compared to this variable

def doKey(key):

  global code
  global pin
  code += key

  if (len(code) == len(pin)):
    if(code == pin):
      print('correct code')
      print("Invalid code")

# doKey will be called each time a keypad button is pressed


1 Answer 1


Make a counter which you will increment in your while(True) loop, and reset to zero in the keypad handler. Once the counter reaches 5s / 0.2s = 25, you will reset the user-entered code to zero before adding new digits to it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.