from machine import Pin, Timer
from time import sleep
class Keypad:
KEY_UP = const(0)
KEY_DOWN = const(1)
keys = [['1', '2', '3', 'A'],
['4', '5', '6', 'B'],
['7', '8', '9', 'C'],
['*', '0', '#', 'D']]
def __init__(self, rows, cols, bufferlenght=100):
self.buffer = ''
self.status = True
self.bufferlenght = bufferlenght
# Set pins for rows as outputs
self.row_pins = [ Pin(pin_name, mode=Pin.OUT, value=0) for pin_name in rows ]
# Set pins for columns as inputs
self.col_pins = [ Pin(pin_name, mode=Pin.IN, pull=Pin.PULL_DOWN) for pin_name in cols ]
Timer(freq=10, callback=self.pollKeypad)
def pollKeypad(self, timer):
key = None
nokey = True
for row in range(4):
for col in range(4):
# Set the current row to high
self.row_pins[row].high()
# Check for key pressed events
if self.col_pins[col].value() == KEY_DOWN:
key = KEY_DOWN
nokey = False
if self.col_pins[col].value() == KEY_UP:
key = KEY_UP
self.row_pins[row].low()
if key == KEY_DOWN and self.status:
self.buffer += self.keys[row][col]
self.status = False
if len(self.buffer)>self.bufferlenght:
self.buffer = self.buffer[-self.bufferlenght:]
if nokey:
self.status = True
def clearBuffer(self):
self.buffer = ''
def getBuffer(self):
return self.buffer
# Initialize and set all the rows to low
rows = [28, 27, 26, 22]
cols = [21, 20, 19, 18]
k = Keypad(rows=rows, cols=cols, bufferlenght=16)
oldtxt = ''
while True:
newtxt = k.getBuffer()
if len(newtxt)>0 and newtxt[-1] == '#':
k.clearBuffer()
newtxt = ''
if newtxt != oldtxt:
print(newtxt)
oldtxt = newtxt
sleep(.1)