import machine
import time
from utime import sleep
# Add a delay of 0.1 seconds to allow for initialization
time.sleep(0.1)
# Initialize GPIO pins for buttons with pull-down resistors
button_pin = machine.Pin(16,machine.Pin.IN,machine.Pin.PULL_DOWN)
button2_pin = machine.Pin(17,machine.Pin.IN,machine.Pin.PULL_DOWN)
button3_pin = machine.Pin(18,machine.Pin.IN,machine.Pin.PULL_DOWN)
# Initialize variables for button press tracking
button_pressed = False # Flag to indicate if a button is pressed
last_button_time_stamp = 0 # Timestamp of the last button press
button_pressed = False
pressed_button_id = -1 # ID of the pressed button
# Define a dictionary to map button pins to their IDs
object_pin_dict = {button_pin: 2 , button2_pin: 1 ,button3_pin: 0 }
# Initialize GPIO pins for MUX control and input reading
s0 = machine.Pin(27,machine.Pin.OUT)
s1 = machine.Pin(28,machine.Pin.OUT)
mux_in = machine.Pin(26,machine.Pin.IN)
# Define LED-related constants
led_start_Pin= 7
num_leds = 9
# Function to extract the ID from a pin object
def PinId(pin):
return int (str(pin)[8:11].rstrip(","))
# Interrupt callback function for button presses
def interrupt_callback(pin):
global last_button_time_stamp
global button_pressed
global pressed_button_id
cur_button_ts = time.ticks_ms()
button_press_delta = cur_button_ts - last_button_time_stamp
if button_press_delta > 200:
last_button_time_stamp = cur_button_ts
button_pressed = True
pressed_button_id = object_pin_dict[pin]
# Function to read the binary value from MUX inputs
def read_switches():
binary_value = 0
for selector_value in range(4):
s0.value(selector_value %2)
s1.value(selector_value//2)
binary_value += 2**selector_value*mux_in.value()
print (binary_value)
return binary_value
input_list = []
# Timer callback function
def timer_callback(t):
global input_list
if len(input_list)>0:
print('timer Triggered ,wrong password')
input_list.clear()
# Define the password
password =[2,0,1]
# Main function
def main():
# Initialize LED objects
led_objects = []
for i in range(num_leds):
led = machine.Pin(led_start_Pin + i,machine.Pin.OUT)
led_objects.append(led)
input_list =[]
global button_pressed
global pressed_button_id
# Set up interrupts for button pins
button_pin.irq(trigger = machine.Pin.IRQ_RISING,handler =interrupt_callback)
button2_pin.irq(trigger = machine.Pin.IRQ_RISING,handler =interrupt_callback)
button3_pin.irq(trigger = machine.Pin.IRQ_RISING,handler =interrupt_callback)
# Main loop
while True:
if button_pressed:
print ('Key pressed :',pressed_button_id)
input_list.append(pressed_button_id)
button_pressed = False
pressed_button_id = -1
if len(input_list) == 3:
if input_list == password:
print ('Enetred correct password ')
switch_val =read_switches()
if switch_val < num_leds:
led_objects[switch_val].toggle()
else:
print("wrong password")
read_switches()
input_list.clear()
# Entry point
if __name__ == '__main__':
main()
# adpted from classroom(udacity)