Hardware Reference
In-Depth Information
# Loop to get a pressed digit
digit = None
while digit == None:
digit = kp.getKey()
The loop uses the getKey() function from the keypad class to continuously poll the
numeric keypad device waiting for the user to press keys and input parts of her code.
Once a key is pressed, the value of digit changes from None to the value of the key
pressed, the value of the digit entered prints, the value for the code to that point (in
the attempt variable) updates, and the code entered so far prints:
# Print the result
print "Digit Entered: %s"%digit
attempt = (attempt[1:] + str(digit))
print "Attempt value: %s"%attempt
Now the program checks to see if the code as entered so far matches the value set in
passcode earlier. If it does, the program prints a happy message and exits:
# Check for passcode match
if (attempt == passcode):
print "Your code was correct, goodbye."
exit()
If it doesn't match the passcode (either because it is incorrect or because not enough
digits have been entered), the program proceeds to the end of the loop, updating the
number of digits entered. If the number of digits in the entered code is more than four,
the program knows the user did not find the correct code in time it restarts the loop.
If it is fewer than four digits, it simply loops again and waits for more digits:
else:
counter += 1
print "Entered digit count: %s"%counter
if (counter >= 4):
print "Incorrect code!"
sleep(3)
print "Try Again"
sleep(1)
counter = 0
sleep(0.5)
This example program plays a simple guessing game, but it illustrates how you can
use the physical numeric keypad as an input device. You could easily modify this code
to unlock a door when the correct code is entered, incorporate it as part of an alarm
system, or use it to take numeric input for a Raspberry Pi-controlled thermostat.
Search WWH ::




Custom Search