from machine import Pin, I2C
from lcd_api import LcdApi
from pico_i2c_lcd import I2cLcd
import time
# I2C and LCD configuration
I2C_ADDR = 0x27
I2C_NUM_ROWS = 2
I2C_NUM_COLS = 16
# Initialize I2C (GP0 = SDA, GP1 = SCL)
i2c = I2C(0, sda=Pin(0), scl=Pin(1), freq=400000)
# Initialize LCD
lcd = I2cLcd(i2c, I2C_ADDR, I2C_NUM_ROWS, I2C_NUM_COLS)
# Initialize button on GP15 with pull-up
button = Pin(15, Pin.IN, Pin.PULL_UP)
# Counter for button presses
press_count = 0
last_button_state = 1
def update_display(line1, line2=""):
"""Update the LCD display with 2 lines of text"""
lcd.clear()
lcd.putstr(line1)
if line2:
lcd.move_to(0, 1)
lcd.putstr(line2)
# Display welcome message
update_display("Raspberry Pico", "Press button!")
print("Program started!")
print("Press the button to increment counter")
# Main loop
while True:
current_button_state = button.value()
# Detect button press (transition from HIGH to LOW)
if last_button_state == 1 and current_button_state == 0:
press_count += 1
print(f"Button pressed! Count: {press_count}")
update_display("Button Pressed!", f"Count: {press_count}")
time.sleep(0.2) # Debounce delay
last_button_state = current_button_state
time.sleep(0.01) # Small delay to reduce CPU usage