4

I have a Keypad 4X4, but my actual code doesn't work. See below:

import RPi.GPIO as GPIO
import time

GPIO.setmode(GPIO.BOARD)
GPIO.setwarnings(False)

MATRIX = [[1,2,3,'A'],
     [4,5,6,'B'],
     [7,8,9,'C'],
     ['*',0,'#','D']]

ROW = [3,5,8,10]
COL = [19,21,23,24]

for j in range(4):
    GPIO.setup(COL[j], GPIO.OUT)
    GPIO.output(COL[j], 1)

for i in range(4):
    GPIO.setup(ROW[i], GPIO.IN, pull_up_down = GPIO.PUD_UP)

try:
    while(True):
        for j in range(4):
            GPIO.output(COL[j],0)


for i in range(4):
    if GPIO.input(ROW[i]) == 0:
        print MATRIX[i][j]
        time.sleep(0.2)
        while(GPIO.input(ROW[i]) == 0):
            pass


    GPIO.output(COL[j],1)
except KeyboardInterupt:
    GPIO.cleanup()

Or somebody knows how to use a keypad in a Raspberry?

3
  • Can you please share the keyboards brand and or a link to where way find it? Commented Aug 17, 2016 at 17:42
  • @MohammadAli I use this type theorycircuit.com/interfacing-4x4-keypad-arduino Commented Aug 18, 2016 at 12:26
  • I installed pad4pi and when i run your test code, program simply closes itself and i end up at the beginning. If i run in terminal sudo python keypadTest.py, program will exit without warnings. When i start program again i get error " This chanell is already in use" ?
    – Emil
    Commented Dec 9, 2016 at 21:29

1 Answer 1

7

I use pad4pi. It simplifies everything. For more details you may want to see githubdemoproject.

from pad4pi import rpi_gpio
import time

# Setup Keypad
KEYPAD = [
        ["1","2","3","A"],
        ["4","5","6","B"],
        ["7","8","9","C"],
        ["*","0","#","D"]
]

# same as calling: factory.create_4_by_4_keypad, still we put here fyi:
ROW_PINS = [4, 14, 15, 17] # BCM numbering
COL_PINS = [18, 27, 22, 23] # BCM numbering

factory = rpi_gpio.KeypadFactory()

# Try factory.create_4_by_3_keypad
# and factory.create_4_by_4_keypad for reasonable defaults
keypad = factory.create_keypad(keypad=KEYPAD, row_pins=ROW_PINS, col_pins=COL_PINS)

#keypad.cleanup()

def printKey(key):
  print(key)
  if (key=="1"):
    print("number")
  elif (key=="A"):
    print("letter")

# printKey will be called each time a keypad button is pressed
keypad.registerKeyPressHandler(printKey)

try:
  while(True):
    time.sleep(0.2)
except:
 keypad.cleanup()

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