Hardware Reference
In-Depth Information
This code will prompt you to enter your four-digit secret code into the numeric keypad.
The code in this example is 8675 . As you enter the digits, it will print out debugging
details showing you the digit entered, the current stored value of your code to that
point, the number of digits in your code that you have entered, and finally, after four
digits have been entered, whether your code is correct.
Nifty, huh? But how does it work? book-demo.py uses the keypad function from the
matrix_keypad_RPi_GPIO module in the matrix_keypad library. The matrix_key
pad_MCP230xx module in the library it is only for when you have an I2C Port Expander
in use. The code also imports the sleep and exit functions from the standard Python
time and sys libraries so the code can sleep briefly if it's entered incorrectly and so
that it can exit if it is entered properly:
from matrix_keypad.matrix_keypad_RPi_GPIO import keypad
from time import sleep
from sys import exit
Now, to silence the GPIO warnings. The Python Raspberry Pi GPIO library emits warn-
ings whenever you have any GPIO pins configured as anything other than input. Since
the matrix_keypad_RPi_GPIO library always configures the column pins as output (low),
you'll get this warning every time you use it. You don't want to see that, so silence it
by disabling the warnings:
import RPi.GPIO as GPIO
GPIO.setwarnings(False)
Now you need to initialize the keypad class from the matrix_keypad_RPi_GPIO module.
This will create a kp variable you can use to read the keys from the physical numeric
keypad. The matrix_keypad_Rpi_GPIO module supports both 3 x 4 and 4 x 4 numeric
keypad devices, but because our hardware is a 3 x 4, we'll tell it that we have only three
columns. We also set up variables to store code attempts, the passcode we are check-
ing for, and a counter variable to track the progress of inputting the code:
kp = keypad(columnCount = 3)
# Setup variables
attempt = "0000"
passcode = "8675"
counter = 0
At this point, the program prints a friendly message to the user to tell her what to do
(input the four-digit secret code) and start a loop:
print 'Enter your four digit secret code into the numeric keypad!'
# Loop while waiting for a keypress
while True:
Search WWH ::




Custom Search