# KeyPad Vers #2
# Tony Goodhew 9th May 2020
# https://www.instructables.com/Using-a-4x4-KeyPad-With-CircuitPython/
#
# Changes by Christopher Scheuring 2022-05-13 for ESP32 support
#
# Connections left to right on KeyPad
# 0   1   2   3   4   5   6   7
# 13  12  14  27  15  02  04  16

from machine import Pin
import gc
import time

gc.collect() # make some room

# Set up LED on pin 17
led_pin = 17

led = Pin(led_pin, Pin.OUT)
led.on() # switch off led - inverted logic!

# Set up Rows
rows = []
for p in [13, 12, 14, 27]:
    row = Pin(p, Pin.OUT)
    rows.append(row)
# anodes OFF
for i in range(4):
    rows[i].off()

# Set up columns
cols = []
for p in [15, 02, 04, 16]:
    col = Pin(p, Pin.IN, Pin.PULL_DOWN)
    cols.append(col)

def getkey():  # Returns -999 or key value
    values = [1,2,3,10, 4,5,6,11, 7,8,9,12, 14,0,15,13]
    val = -999 # Error value for no key press
    for count in range(10): # Try to get key press 10 times
        for r in range(4):  # Rows, one at a time
            rows[r].on() # row HIGH
            for c in range(4): # Test columns, one at a time
                if cols[c].value() == 1: # Is column HIGH?
                    p = r * 4 + c      # Pointer to values list
                    val = values[p]
                    count = 11 # This stops looping
                    led.off() # Flash LED ON if key pressed
            rows[r].off() # row LOW
    time.sleep(0.2) # Debounce
    led.on() # LED OFF
    return val

def getvalue(digits): # Number of digits
    result = 0
    count = 0
    while True:
        x = getkey()
        if x != -999 and x < 10: # Check if numeric key pressed
            result = result * 10 + x
            print(result)
            count = count + 1
        if count == digits:
            return result

# +++++ Main +++++
print("Press 4 numeric (BLUE) keys")
y = getvalue(4)
print('\n',y)

print("\nPress any of the keys\n # halts the program")

characters =["1","2","3","4","5","6","7","8","9","A","B","C","D","*","#","0"]
running = True
while running:
    x = getkey()
    if x != -999: # A key has been pressed!
        print(characters[x-1])
        if x == 15:
            running = False
            
led.on()
