import time
from machine import Pin,I2C
from lcd_api import LcdApi
from i2c_lcd import I2cLcd
i2c = I2C(0, sda=Pin(0), scl=Pin(1), freq=400000)
I2C_ADDR = 0x27
lcd= I2cLcd(i2c, I2C_ADDR, 2, 16)
ROW = [13, 12, 11, 10]
COL = [9, 8, 7, 6]
KEYS = [
["1", "2", "3", "+"],
["4", "5", "6", "-"],
["7", "8", "9", "*"],
["C", "0", "=", "/"]
]
rows = [Pin(pin, Pin.OUT) for pin in ROW]
cols = [Pin(pin, Pin.IN, Pin.PULL_DOWN) for pin in COL]
def check_keypad():
for i, row in enumerate(rows):
for r in rows:
r.value(0)
row.value(1)
for j, col in enumerate(cols):
if col.value() == 1:
return KEYS[i][j]
return None
num1 = ""
num2 = ""
operator = ""
last_key = None
lcd.clear()
while True:
key = check_keypad()
if key != last_key:
if key is not None:
print("Key:", key)
if key == "C":
num1 = ""
num2 = ""
operator = ""
print("Cleared")
lcd.clear()
elif key in ["+", "-", "*", "/"]:
operator = key
print("Operator:", operator)
lcd.putstr(str(operator))
elif key == "=":
if num1 != "" and num2 != "" and operator != "":
a = int(num1)
b = int(num2)
if operator == "+":
result = a + b
elif operator == "-":
result = a - b
elif operator == "*":
result = a * b
elif operator == "/":
result = a / b
print("Result:", result)
lcd.putstr("=")
lcd.move_to(0,1)
lcd.putstr(str(result))
num1 = ""
num2 = ""
operator = ""
else:
if operator == "":
num1 += key
print("Num1:", num1)
lcd.putstr(str(key))
else:
num2 += key
print("Num2:", num2)
lcd.putstr(str(key))
last_key = key
time.sleep(0.2)