import Adafruit_BBIO.GPIO as GPIO
import time 
import sys

KEYPAD = [
    ["1","2","3"],
    ["4","5","6"],
    ["7","8","9"],
    ["*","0","#"]
]

ROW         = ["P8_8", "P8_10", "P8_12", "P8_14"]
COLUMN      = ["P8_16", "P8_17", "P8_18"]

pin_r1 = "P8_8"
pin_r2 = "P8_10"
pin_r3 = "P8_12"
pin_r4 = "P8_14"

pin_c1 = "P8_16"
pin_c2 = "P8_17"
pin_c3 = "P8_18"

GPIO.setup(pin_r1, GPIO.OUT)
GPIO.setup(pin_r2, GPIO.OUT)
GPIO.setup(pin_r3, GPIO.OUT)
GPIO.setup(pin_r4, GPIO.OUT)
GPIO.setup(pin_c1, GPIO.IN)
GPIO.setup(pin_c2, GPIO.IN)
GPIO.setup(pin_c3, GPIO.IN)

def cb_keypressed(pin):
    col = COLUMN.index(pin)
    key = None

    # GPIO.output(pin_r1, GPIO.HIGH)
    GPIO.output(pin_r2, GPIO.LOW)
    GPIO.output(pin_r3, GPIO.LOW)
    GPIO.output(pin_r4, GPIO.LOW)
    if GPIO.input(pin):
        key=KEYPAD[0][col]

    GPIO.output(pin_r1, GPIO.LOW)
    GPIO.output(pin_r2, GPIO.HIGH)
    # GPIO.output(pin_r3, GPIO.LOW)
    # GPIO.output(pin_r4, GPIO.LOW)
    if GPIO.input(pin):
        key=KEYPAD[1][col]
    

    # GPIO.output(pin_r1, GPIO.LOW)
    GPIO.output(pin_r2, GPIO.LOW)
    GPIO.output(pin_r3, GPIO.HIGH)
    # GPIO.output(pin_r4, GPIO.LOW)
    if GPIO.input(pin):
        key=KEYPAD[2][col]

    # GPIO.output(pin_r1, GPIO.LOW)
    # GPIO.output(pin_r2, GPIO.LOW)
    GPIO.output(pin_r3, GPIO.LOW)
    GPIO.output(pin_r4, GPIO.HIGH)
    if GPIO.input(pin):
        key=KEYPAD[3][col]

    if key:
        print(key)
    
    GPIO.output(pin_r1, GPIO.HIGH)
    GPIO.output(pin_r2, GPIO.HIGH)
    GPIO.output(pin_r3, GPIO.HIGH)
    GPIO.output(pin_r4, GPIO.HIGH)

GPIO.add_event_detect(pin_c1, GPIO.RISING, callback=cb_keypressed, bouncetime=50)
GPIO.add_event_detect(pin_c2, GPIO.RISING, callback=cb_keypressed, bouncetime=50)
GPIO.add_event_detect(pin_c3, GPIO.RISING, callback=cb_keypressed, bouncetime=50)
    
try:
    GPIO.output(pin_r1, GPIO.HIGH)
    GPIO.output(pin_r2, GPIO.HIGH)
    GPIO.output(pin_r3, GPIO.HIGH)
    GPIO.output(pin_r4, GPIO.HIGH)
    time.sleep(1)
    print("...")
    while True:
        time.sleep(2)
        print("...")

except Exception as e:
    print("Exception captured. Clean up and quit...")
    GPIO.cleanup()
    print(e)
