from machine import Pin
import utime
# Define pin assignments for rows and columns
keypad_rows = [9, 8, 7, 6]
keypad_cols = [5, 4, 3, 2]
# Create lists for row and column pins
row_pins = [Pin(x, Pin.OUT) for x in keypad_rows]
col_pins = [Pin(x, Pin.IN, Pin.PULL_DOWN) for x in keypad_cols]
# Define keypad matrix
keypad_map = [
['1', '2', '3', 'A'],
['4', '5', '6', 'B'],
['7', '8', '9', 'C'],
['*', '0', '#', 'D']
]
# Create a pin for the LED
led_pin10 = Pin(10, Pin.OUT)
led_pin11 = Pin(11, Pin.OUT)
led_pin12 = Pin(12, Pin.OUT)
led_pin13 = Pin(13, Pin.OUT)
led_pin14 = Pin(14, Pin.OUT)
led_pin15 = Pin(15, Pin.OUT)
led_pin16 = Pin(16, Pin.OUT)
led_pin17 = Pin(17, Pin.OUT)
led_pin18 = Pin(18, Pin.OUT)
# Define switch pin
switch_pin = Pin(28, Pin.IN, Pin.PULL_UP)
def scan_keypad():
if switch_pin.value() == 0:
# Switch is off, disable keypad input
return None
for row in range(4):
row_pins[row].high()
for col in range(4):
if col_pins[col].value() == 1:
key = keypad_map[row][col]
# Toggle LED state when key "1" is pressed
if key == '1':
led_pin15.value(not led_pin15.value())
if key == '2':
led_pin14.value(not led_pin14.value())
if key == '3':
led_pin13.value(not led_pin13.value())
if key == '4':
led_pin12.value(not led_pin12.value())
if key == '5':
led_pin11.value(not led_pin11.value())
if key == '6':
led_pin10.value(not led_pin10.value())
if key == '7':
led_pin16.value(not led_pin16.value())
if key == '8':
led_pin17.value(not led_pin17.value())
if key == '9':
led_pin18.value(not led_pin18.value())
print(f"Key pressed: {key}")
return key
row_pins[row].low()
while True:
key = scan_keypad()
utime.sleep(0.2) # Debounce delay