import machine
import time
from utime import sleep
# The button pins (GPIO16, GPIO17, GPIO18 with PULL_DOWN)
b0 = machine.Pin(16, machine.Pin.IN, machine.Pin.PULL_DOWN)
b1 = machine.Pin(17, machine.Pin.IN, machine.Pin.PULL_DOWN)
b2 = machine.Pin(18, machine.Pin.IN, machine.Pin.PULL_DOWN)
s0 = machine.Pin(27, machine.Pin.OUT)
s1 = machine.Pin(28, machine.Pin.OUT)
MUX_IN = machine.Pin(26, machine.Pin.IN, machine.Pin.PULL_DOWN)
led_pins = [7, 8, 9, 10, 11, 12, 13, 14, 15]
leds = [machine.Pin(pin, machine.Pin.OUT) for pin in led_pins]
def toggle_led(index):
leds[index].value(not leds[index].value())
last_press_time = 0
correct_sequence = [b0, b2, b1]
user_sequence = []
last_decimal = -1
def button_callback(pin):
global last_press_time, correct_sequence, user_sequence, last_decimal
current_time = time.ticks_ms()
# Checking if the time difference is greater than 200ms
if time.ticks_diff(current_time, last_press_time) > 200:
last_press_time = current_time
if pin is b0:
print("B0 is pressed!")
elif pin is b1:
print("B1 is pressed!")
elif pin is b2:
print("B2 is pressed!")
user_sequence.append(pin)
if len(user_sequence) == 3:
if user_sequence == correct_sequence:
print("Passcode is correct")
if 0 <= last_decimal <= 8:
print("Toggling : {}".format(last_decimal))
toggle_led(last_decimal)
else:
print("Selected output {} out of range. Correct range is [0-8].".format(last_decimal))
else:
print("Passcode is wrong.Try again.")
user_sequence.clear()
# Make interrupts to the buttons
b0.irq(trigger=machine.Pin.IRQ_RISING, handler=button_callback)
b1.irq(trigger=machine.Pin.IRQ_RISING, handler=button_callback)
b2.irq(trigger=machine.Pin.IRQ_RISING, handler=button_callback)
while True:
decimal_value = 0
for channel in range(4):
s0.value(channel & 1)
s1.value((channel >> 1) & 1)
time.sleep(0.01)
bit = MUX_IN.value()
decimal_value += bit * (2 ** (channel))
if decimal_value != last_decimal:
last_decimal = decimal_value
print("Selected output:", decimal_value)
time.sleep(0.1)SW0
SW2
SW3
SW1
B2
B0
B1