'''
PIN13 - R1 (OUTPUT)
PIN14 - R2 (OUTPUT)
PIN15 - R3 (OUTPUT)
PIN16 - R4 (OUTPUT)
PIN32 - C1 (INPUT)
PIN33 - C2 (INPUT)
PIN34 - C3 (INPUT)
PIN35 - C4 (INPUT)
'''
'''
from machine import mem32
import time
GPIO_OUT_W1TS_REG = 0x3FF44008
GPIO_OUT_W1TC_REG = 0x3FF4400C
GPIO_ENABLE_REGISTER = 0x3FF44020
GPIO5 = 5
mem32[GPIO_ENABLE_REGISTER] |= 1 << GPIO5
while True:
mem32[GPIO_OUT_W1TS_REG] |= 1 << GPIO5
print("LED ON")
# delay
time.sleep(1)
mem32[GPIO_OUT_W1TC_REG] |= 1 << GPIO5
print("LED OFF")
#delay
time.sleep(1)
'''
import machine
import time
# GPIO specifics for rows and columns
ROWS = [13, 14, 15, 16]
COLS = [32, 33, 34, 35]
# Register base addresses
GPIO_ENABLE_REG = 0x3FF44020 # GPIO direction register
GPIO_OUT_W1TS_REG = 0x3FF44008 # GPIO write 1 to set register
GPIO_OUT_W1TC_REG = 0x3FF4400C # GPIO write 1 to clear register
GPIO_IN_REG = 0x3FF4403C # GPIO input register
GPIO_PIN_BASE = 0x3FF44000 # Base for GPIO_PINn_REG
# Configure row pins as output
for row in ROWS:
print(f"Configuring GPIO{row} as output.")
machine.mem32[GPIO_ENABLE_REG] |= (1 << row) # Set as output
machine.mem32[GPIO_OUT_W1TC_REG] |= (1 << row) # Initially set LOW
# Configure column pins as input with pull-up resistors using registers
for col in COLS:
print(f"Configuring GPIO{col} as input with pull-up.")
pin_reg = GPIO_PIN_BASE + (col * 0x04) # Address of GPIO_PINn_REG
machine.mem32[pin_reg] |= (1 << 2) # Enable pull-up resistor
# Keypad layout (customize based on your keypad)
KEYPAD = [
['1', '2', '3', 'A'],
['4', '5', '6', 'B'],
['7', '8', '9', 'C'],
['*', '0', '#', 'D']
]
def scan_keypad():
for row_idx, row_pin in enumerate(ROWS):
# Activate the current row (set HIGH)
print(f"Activating row GPIO{row_pin}.")
machine.mem32[GPIO_OUT_W1TS_REG] = (1 << row_pin)
# Read columns to detect keypress
for col_idx, col_pin in enumerate(COLS):
col_state = machine.mem32[GPIO_IN_REG] & (1 << col_pin)
print(f"Checking column GPIO{col_pin}: {'HIGH' if col_state else 'LOW'}.")
if not col_state: # If column is LOW
print(f"Key pressed: Row {row_idx}, Col {col_idx}.")
# Deactivate the current row (set LOW)
machine.mem32[GPIO_OUT_W1TC_REG] = (1 << row_pin)
return KEYPAD[row_idx][col_idx] # Return key pressed
# Deactivate the current row (set LOW)
print(f"Deactivating row GPIO{row_pin}.")
machine.mem32[GPIO_OUT_W1TC_REG] = (1 << row_pin)
return None # No key pressed
# Main loop to read the keypad
while True:
key = scan_keypad()
if key:
print(f"Key Pressed: {key}")
else:
print("No key pressed.")
time.sleep(0.1) # Small delay to debounce