# Step 1: Import necessary modules
from machine import SoftI2C, Pin
from utime import sleep
from i2c_lcd import I2cLcd
import time
# I2C address of the LCD
AddressOfLcd = 0x27
# Initialize I2C for the LCD
i2c = SoftI2C(scl=Pin(22), sda=Pin(21), freq=400000) # connect scl to GPIO 22, sda to GPIO 21
# Initialize the LCD
lcd = I2cLcd(i2c, AddressOfLcd, 2, 16)
# Define GPIO pins for rows
row_pins = [Pin(15, Pin.OUT), Pin(2, Pin.OUT), Pin(4, Pin.OUT), Pin(5, Pin.OUT)]
# Define GPIO pins for columns (changed to 16 and 17)
column_pins = [Pin(18, Pin.IN, Pin.PULL_DOWN), Pin(19, Pin.IN, Pin.PULL_DOWN), Pin(26, Pin.IN, Pin.PULL_DOWN), Pin(27, Pin.IN, Pin.PULL_DOWN)]
# Define keypad layout
keys = [
['1', '2', '3', 'A'],
['4', '5', '6', 'B'],
['7', '8', '9', 'C'],
['*', '0', '#', 'D']
]
# Function to read the keypad
def read_keypad():
for row_num, row_pin in enumerate(row_pins):
row_pin.on()
for col_num, col_pin in enumerate(column_pins):
if col_pin.value() == 1:
row_pin.off()
return keys[row_num][col_num]
row_pin.off()
return None
# Function to display text on the LCD
def display_text(line1, line2=""):
lcd.clear()
lcd.move_to(0, 0)
lcd.putstr(line1)
lcd.move_to(0, 1)
lcd.putstr(line2)
# Function to get a number from the keypad
def get_number():
num = ''
while True:
key = read_keypad()
if key:
if key in '0123456789':
num += key
display_text(num)
elif key == '#': # Confirm the number
return int(num)
elif key == '*': # Clear the current number
num = ''
display_text(num)
sleep(0.2) # Debounce delay
# Main calculator logic
def calculator():
while True:
display_text('Enter a:')
a = get_number()
display_text('Enter b:')
b = get_number()
display_text('Op: + - * /')
while True:
op = read_keypad()
if op in 'ABCD':
break
if op == 'A': # Addition
result = a + b
op_str = '+'
elif op == 'B': # Subtraction
result = a - b
op_str = '-'
elif op == 'C': # Multiplication
result = a * b
op_str = '*'
elif op == 'D': # Division
if b != 0:
result = a / b
else:
result = 'Err'
op_str = '/'
display_text(f'{a}{op_str}{b}=', str(result))
sleep(5) # Display the result for 5 seconds
# Start the calculator
calculator()