import time
import board
import digitalio
# -------------------------
# Keypad setup (4x4)
# -------------------------
rows = [board.GP13, board.GP12, board.GP11, board.GP10]
cols = [board.GP9, board.GP8, board.GP7, board.GP6]
row_pins = []
col_pins = []
for r in rows:
pin = digitalio.DigitalInOut(r)
pin.direction = digitalio.Direction.OUTPUT
pin.value = True
row_pins.append(pin)
for c in cols:
pin = digitalio.DigitalInOut(c)
pin.direction = digitalio.Direction.INPUT
pin.pull = digitalio.Pull.UP
col_pins.append(pin)
# Key map
keys = [
['1','2','3','A'],
['4','5','6','B'],
['7','8','9','C'],
['*','0','#','D']
]
# -------------------------
# 7-Segment Character Map
# a,b,c,d,e,f,g
# -------------------------
segments = {
'0': [1,1,1,1,1,1,0],
'1': [0,1,1,0,0,0,0],
'2': [1,1,0,1,1,0,1],
'3': [1,1,1,1,0,0,1],
'4': [0,1,1,0,0,1,1],
'5': [1,0,1,1,0,1,1],
'6': [1,0,1,1,1,1,1],
'7': [1,1,1,0,0,0,0],
'8': [1,1,1,1,1,1,1],
'9': [1,1,1,1,0,1,1],
'A': [1,1,1,0,1,1,1],
'B': [0,0,1,1,1,1,1],
'C': [0,0,0,1,1,0,1],
'D': [0,1,1,1,1,0,1],
'-': [0,0,0,0,0,0,1],
'h': [0,1,1,0,1,1,1],
' ': [0,0,0,0,0,0,0]
}
# -------------------------
# Segment pins
# -------------------------
seg_pins = [
board.GP16, # a
board.GP17, # b
board.GP18, # c
board.GP19, # d
board.GP20, # e
board.GP21, # f
board.GP22 # g
]
seg_outputs = []
for p in seg_pins:
pin = digitalio.DigitalInOut(p)
pin.direction = digitalio.Direction.OUTPUT
seg_outputs.append(pin)
# -------------------------
# Display function
# -------------------------
def display(char):
pattern = segments.get(char, segments[' '])
for i in range(7):
seg_outputs[i].value = pattern[i]
# -------------------------
# Keypad Scanning Logic
# (Added to make the code functional)
# -------------------------
def scan_keypad():
for row_num, row_pin in enumerate(row_pins):
row_pin.value = False # Set current row to LOW
for col_num, col_pin in enumerate(col_pins):
if not col_pin.value: # If column is LOW, key is pressed
row_pin.value = True # Reset row before returning
return keys[row_num][col_num]
row_pin.value = True # Reset row to HIGH
return None
# -------------------------
# Main loop
# -------------------------
last_key = None
while True:
key = scan_keypad()
if key and key != last_key:
print("Key:", key)
# ---- Numeric ----
if key.isdigit():
display(key)
# ---- A-D ----
elif key in ['A','B','C','D']:
display(key)
# ---- Special ----
elif key == '*':
display('-')
elif key == '#':
display('h')
last_key = key
if not key:
last_key = None # reset when released
time.sleep(0.05)