from machine import Pin
import time
## LCD Pins
# Control pins
rs = Pin(2, Pin.OUT)
rw = Pin(3, Pin.OUT)
en = Pin(4, Pin.OUT)
# Data pins D4–D7
# Data pins D4–D7
d4 = Pin(5, Pin.OUT)
d5 = Pin(6, Pin.OUT)
d6 = Pin(7, Pin.OUT)
d7 = Pin(8, Pin.OUT)
data_pins = [d4, d5, d6, d7]
## Keypad Pins
# -------------------------------
# Keypad configuration (4x4)
# -------------------------------
rows = [
Pin(16, Pin.OUT, Pin.PULL_DOWN),
Pin(17, Pin.OUT, Pin.PULL_DOWN),
Pin(18, Pin.OUT, Pin.PULL_DOWN),
Pin(19, Pin.OUT, Pin.PULL_DOWN)
]
cols = [
Pin(20, Pin.IN, Pin.PULL_DOWN),
Pin(21, Pin.IN, Pin.PULL_DOWN),
Pin(22, Pin.IN, Pin.PULL_DOWN),
Pin(26, Pin.IN, Pin.PULL_DOWN)
]
keys = [
['1', '2', '3', 'A'],
['4', '5', '6', 'B'],
['7', '8', '9', 'C'],
['*', '0', '#', 'D']
]
# -------------------------------
# Keypad scanning function
# -------------------------------
def read_key():
for r in range(4):
rows[r].value(1)
for c in range(4):
if cols[c].value() == 1:
rows[r].value(0)
return keys[r][c]
rows[r].value(0)
return None
# Enable pulse
def pulse_enable():
en.value(1)
time.sleep_us(1)
en.value(0)
time.sleep_us(1)
# Read Busy Flag (BF = D7)
def lcd_busy_wait():
rs.value(0) # Command register
rw.value(1) # Read mode
d7.init(Pin.IN)
while True:
# Read high nibble (BF is D7)
en.value(1)
time.sleep_us(1)
busy = d7.value()
en.value(0)
time.sleep_us(1)
# Read low nibble (discarded but REQUIRED)
en.value(1)
time.sleep_us(1)
en.value(0)
time.sleep_us(1)
if busy == 0:
break
d7.init(Pin.OUT)
rw.value(0) # Back to write mode
def send_nibble(nibble):
for i in range(4):
data_pins[i].value((nibble >> i) & 1)
pulse_enable()
def send_byte(value, mode):
lcd_busy_wait()
rs.value(mode)
rw.value(0)
send_nibble(value >> 4)
send_nibble(value & 0x0F)
def lcd_init():
time.sleep_ms(20)
send_nibble(0x03)
time.sleep_ms(5)
send_nibble(0x03)
time.sleep_us(150)
send_nibble(0x02)
send_byte(0x28, 0) # 4-bit, 2-line
send_byte(0x0C, 0) # Display ON
send_byte(0x06, 0) # Entry mode
send_byte(0x01, 0) # Clear display
def lcd_print(text):
for c in text:
send_byte(ord(c), 1)
# -------------------------------
# Main loop
# -------------------------------
lcd_init()
while True:
key = read_key()
if key:
print("Key pressed:", key)
lcd_print(key)
time.sleep(0.3) # debounce delay
Loading
pi-pico-w
pi-pico-w