# Libraries
from machine import I2C, Pin
from time import sleep
from pico_i2c_lcd import I2cLcd
import time
import utime
# Pin Initialization
button = Pin(17, Pin.IN, Pin.PULL_DOWN)
clear = Pin(19, Pin.IN, Pin.PULL_DOWN)
i2c = I2C(0, sda=Pin(0), scl=Pin(1), freq=400000)
I2C_ADDR = i2c.scan()[0]
lcd = I2cLcd(i2c, I2C_ADDR, 4, 20)
# Variable Initialization
display = "I2C Address:"+str(I2C_ADDR)+"\n"
previous_display = ""
calc = ""
result = ""
# CONSTANTS
KEY_UP = const(0)
KEY_DOWN = const(1)
keys = [['1', '2', '3', '+'], ['4', '5', '6', '-'], [7, 8, 9, '*'], ['.', 0, '=', '/']]
# RPi Pico pin assignments
rows = [8,9,10,11]
cols = [12,13,15,16]
# Set pins for rows as outputs
row_pins = [Pin(pin_name, mode=Pin.OUT) for pin_name in rows]
# Set pins for columns as inputs
col_pins = [Pin(pin_name, mode=Pin.IN, pull=Pin.PULL_DOWN) for pin_name in cols]
# Keypad Functions
def InitKeypad():
for row in range(0,4):
for col in range(0,4):
row_pins[row].low()
def PollKeypad():
key = None
keys_down = []
for row in range(4):
for col in range(4):
# Set the current row to high
row_pins[row].high()
# Check for key pressed events
if col_pins[col].value() == KEY_DOWN:
key = KEY_DOWN
if col_pins[col].value() == KEY_UP:
key = KEY_UP
row_pins[row].low()
if key == KEY_DOWN:
keys_down.append(keys[row][col])
return keys_down
# Initialize and set all the rows to low
InitKeypad()
# UPDATE DISPLAY FUNCTION
def update_display(txt):
global previous_display
if(previous_display!=txt):
lcd.clear()
lcd.putstr(txt)
previous_display = txt
# Main Loop
while True:
# LED and Button
if button.value():
led.toggle()
time.sleep(0.5)
if clear.value():
calc = ""
result = ""
time.sleep(0.5)
# LCD
to_display = ""
if PollKeypad() != []:
if '=' in PollKeypad():
result = '\n = ' + str(eval(calc))
to_display = calc + result
else:
result = ""
calc += str(PollKeypad()).replace('[','').replace(']','').replace("'",'')
to_display = calc + result
time.sleep(0.5)
else: to_display = calc + result
update_display(to_display)