from machine import Pin
import time
pIn=Pin.IN
pUp=Pin.PULL_UP
pOut=Pin.OUT
p_row=[Pin(18,pIn,pUp),Pin(5,pIn,pUp),Pin(17,pIn,pUp),Pin(16,pIn,pUp)]
p_col=[Pin(19,pOut),Pin(21,pOut),Pin(22,pOut),Pin(23,pOut)]
n_row=[14,13,11,7] #binary: 1110, 1101, 1011, 0111
keypad=(('1','2','3','A'),
('4','5','6','B'),
('7','8','9','C'),
('*','0','#','D'))
for col in range(4):
p_col[col].on()
while 1:
for col in range(4):
p_col[col].off()
key=(
(p_row[3].value()<<3)
|(p_row[2].value()<<2)
|(p_row[1].value()<<1)
|(p_row[0].value())
)
p_col[col].on()
if key!=15: #if any key is pressed (15 is 1111 in binary)
if key in n_row:
row=n_row.index(key) #row = index of key i.e. [14,13,11,7]
print("key:",keypad[row][col])
time.sleep_ms(200)
time.sleep_ms(10)