In this lesson we show you how to create a Python Class and Library that allows you to easily get user input on a Raspberry Pi from a 16 button keypad. This will allow very easy interaction with the keypad.
The Library Code which we develop in the video is presented below for your convenience:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 | class keypad: def __init__(self,rows=[11,13,15,29],columns=[31,33,35,37],keyLabels=[['1','2','3','A'],['4','5','6','B'],['7','8','9','C'],['*','0','#','D']],retChar='D'): import RPi.GPIO as GPIO self.rows=rows self.columns=columns self.retChar=retChar self.keyLabels=keyLabels GPIO.setmode(GPIO.BOARD) for i in rows: GPIO.setup(i,GPIO.OUT) for j in columns: GPIO.setup(j,GPIO.IN,pull_up_down=GPIO.PUD_DOWN) def readKeypad(self): from time import sleep import RPi.GPIO as GPIO keyStrokes='' noPress=True noPressOld=True while True: noPress=True for myRow in [0,1,2,3]: for myColumn in [0,1,2,3]: GPIO.output(self.rows[myRow],GPIO.HIGH) butVal=GPIO.input(self.columns[myColumn]) GPIO.output(self.rows[myRow],GPIO.LOW) if butVal==1: myChar=self.keyLabels[myRow][myColumn] if myChar==self.retChar: return keyStrokes noPress=False if butVal==1 and noPressOld==True and noPress==False: keyStrokes=keyStrokes+myChar noPressOld=noPress sleep(.25) |
To use this code as a library, save it in the same folder as your python programs, and save it as KPLIB.py
1 2 3 4 5 6 | import RPi.GPIO as GPIO from KPLIB import keypad myPad=keypad(retChar='A') myString=myPad.readKeypad() print(myString) GPIO.cleanup() |
This is a simple demo program that calls the library above, to receive input from the keypad.