from machine import Pin, I2C
import ssd1306
import time
# ESP32 Pin assignment
i2c = I2C(0, scl=Pin(22), sda=Pin(21))
#display
oled_width = 128
oled_height = 64
oled = ssd1306.SSD1306_I2C(oled_width, oled_height, i2c)
# Define the GPIO pins for rows and columns
row_pins = [19, 18, 5, 17]
col_pins = [16, 4, 0, 2]
# Define the keypad matrix
keys = [
['1', '2', '3', '+'],
['4', '5', '6', '-'],
['7', '8', '9', '*'],
['C', '0', '=', '/']
]
# Initialize the row pins as input with pull-up
row_pins_objects = [Pin(pin, Pin.IN, Pin.PULL_UP) for pin in row_pins]
# Initialize the column pins as output
col_pins_objects = [Pin(pin, Pin.OUT) for pin in col_pins]
def read_keypad():
key = None
# Scan each column
for i, col_pin in enumerate(col_pins_objects):
col_pin.value(0) # Set the current column to low
# Check each row for a pressed key
for j, row_pin in enumerate(row_pins_objects):
if row_pin.value() == 0:
key = keys[j][i]
break
col_pin.value(1) # Set the current column back to high
return key
result = 0
num1 = []
num2 = []
operand = ''
secondNum = False
# Main loop
while True:
key_pressed = read_keypad()
if key_pressed:
if key_pressed == '=':
if operand == '+':
result = int(''.join(num1)) + int(''.join(num2))
elif operand == '-':
result = int(''.join(num1)) - int(''.join(num2))
elif operand == '*':
result = int(''.join(num1)) * int(''.join(num2))
elif operand == '/' and int(''.join(num2)) > 0:
result = int(''.join(num1)) / int(''.join(num2))
oled.text(''.join(num1), 0, 0)
oled.text(operand, 0, 10)
oled.text(''.join(num2), 0, 20)
oled.text(key_pressed, 0, 30)
oled.text(str(result), 0, 40)
oled.show()
else:
if not secondNum:
# print("Key pressed:", key_pressed)
if key_pressed not in ['+', '-', '*', '/']:
num1.append(str(key_pressed))
oled.text(''.join(num1), 0, 0)
oled.show()
if key_pressed in ['+', '-', '*', '/']:
secondNum = True
operand = key_pressed
oled.text(''.join(num1), 0, 0)
oled.text(operand, 0, 10)
oled.show()
else:
num2.append(str(key_pressed))
oled.text(''.join(num1), 0, 0)
oled.text(operand, 0, 10)
oled.text(''.join(num2), 0, 20)
oled.show()
if key_pressed == 'C':
oled.fill(0)
oled.show()
num1.clear()
num2.clear()
result = 0
operand = ''
secondNum = False
oled.fill(0)
time.sleep(0.1) # Add a short delay to avoid rapid key detection
# number1 = int(input('Enter a number: '))
# number2 = int(input('Enter a second number: '))
# #print on the display
# oled.text(str(number1 + number2), 55, 20)
# oled.show()