from machine import Pin, I2C
from ssd1306 import SSD1306_I2C

import machine
import sys
import utime

board = sys.implementation._machine.split(' with')[0]
print(f"Running on {board} ({sys.platform}) at {machine.freq() / 1000000} MHz")

pix_res_x = 128
pix_res_y = 64

def init_i2c(scl_pin, sda_pin):
    # Initialize I2C device
    i2c_dev = I2C(1, scl=Pin(scl_pin), sda=Pin(sda_pin), freq=200000)
    i2c_addr = [hex(ii) for ii in i2c_dev.scan()]
    
    if not i2c_addr:
        print('No I2C Display Found')
        sys.exit()
    else:
        print("I2C Address      : {}".format(i2c_addr[0]))
        print("I2C Configuration: {}".format(i2c_dev))
    
    return i2c_dev

# Create a map between keypad buttons and characters
matrix_keys = [['1', '2', '3', 'A'],
               ['4', '5', '6', 'B'],
               ['7', '8', '9', 'C'],
               ['*', '0', '#', 'D']]

# PINs according to schematic - Change the pins to match with your connections
keypad_rows = [19,18,5,17]
keypad_columns = [16,4,0,2]

# Create two empty lists to set up pins ( Rows output and columns input )
col_pins = []
row_pins = []

# Loop to assign GPIO pins and setup input and outputs
for x in range(0,4):
    row_pins.append(Pin(keypad_rows[x], Pin.OUT))
    row_pins[x].value(1)
    col_pins.append(Pin(keypad_columns[x], Pin.IN, Pin.PULL_DOWN))
    col_pins[x].value(0)
    
def scankeys(oled):  
    for row in range(4):
        for col in range(4):
            row_pins[row].value(1)
            key = None
            
            if col_pins[col].value() == 1:
                print("You have pressed:", matrix_keys[row][col])
                key_press = matrix_keys[row][col]
                utime.sleep(1)

                oled.fill(0)
                oled.text("You have.    ", 0, 40)
                oled.text("pressed:     ", 0, 50)
                oled.text(str(key_press), 64, 50)
                oled.show()

                utime.sleep_ms(1)
                                    
        row_pins[row].value(0)

def display_text(oled):
    # Display text on the OLED
    oled.fill(0)
    oled.text("Please enter a", 0, 5)
    oled.text("key from the", 0, 15)
    oled.text("keypad", 0, 25)
    oled.show()

def main():
    i2c_dev = init_i2c(scl_pin=22, sda_pin=21)
    oled = SSD1306_I2C(pix_res_x, pix_res_y, i2c_dev)
    display_text(oled)
    
    print("Please enter a key from the keypad")

    while True:
        scankeys(oled)


if __name__ == '__main__':
    main()