loop()
e xcept KeyboardInterrupt: #When 'Ctrl+C' is pressed, exit the program.
GPIO.cleanup()
In this project code, we use two custom module "Keypad.py", which is located in the same directory with
program file "MatrixKeypad.py". And this library file, which is transplanted from Arduino function library
Keypad, provides a method to read the keyboard. By using this library, we can easily read the matrix keyboard.
First, import module Keypad. Then define the information of the matrix keyboard used in this project: the
number of rows and columns, code of each key and GPIO pin connected to each column and each row.
im port Keypad #import module Keypad
ROWS = 4 #number of rows of the Keypad
COLS = 4 #number of columns of the Keypad
keys = [ '1', '2','3','A', #key code
'4','5','6','B',
'7','8','9','C',
'*','0','#','D' ]
rowsPins = [ 12, 16,18,22] #connect to the row pinouts of the keypad
colsPins = [ 19, 15,13,11] #connect to the column pinouts of the keypad
And then, based on the above information, instantiate a Keypad class object to operate the matrix keyboard.
keypad = Keypad. Keypad(keys,rowsPins,colsPins,ROWS,COLS)
Set the debounce time to 50ms, and this value can be set based on the actual use of the keyboard flexibly,
with default time 10ms.
keypad.setDebounceTime(50)
In the "while" cycle, use the function key= keypad.getKey () to read the keyboard constantly. If there is a key
pressed, its key code will be stored in the variable "key", and then be printed out.
w hile(True):
key = keypad. getKey() #get the state of keys
if(key != keypad.NULL): # if a key is pressed, print out its key code
print ("You Pressed Key : %c "%(key))