4drimport machine
import time
from utime import sleep
sleep(0.02)
start_button_GPIO = 16
start_LED_GPIO = 7
button_count = 3
LED_count = 9
sel_states = 2
last_button_time_click = 0
key_presses = []
## Pin interrupt handler
#
# A function to handle pin interrupts
# Expects a machine.Pin type parameter
def PinId(pin):
return int(str(pin)[8:10].rstrip(","))
def interrupt_callback(pin):
global last_button_time_click
program_start = time.ticks_ms()
time_between_buttons = program_start - last_button_time_click
if time_between_buttons > 200:
last_button_time_click = program_start
key_presses.append(pin)
print(f'Pressed button: {PinId(pin) - start_button_GPIO} ')
def main():
global key_presses
# a tiny sleep to allow the first print to be displayed
sleep(0.01)
print('Program starting')
LED_selected_colour = ["Cyan", "Light Green", "Pink", "Purple", "White", "Orange", "Yellow", "Blue", "Green"]
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)
buttons = []
for plus_but_id in range(button_count):
buttons.append(machine.Pin(plus_but_id + start_button_GPIO, machine.Pin.IN, machine.Pin.PULL_DOWN))
buttons[-1].irq(trigger=machine.Pin.IRQ_FALLING, handler=interrupt_callback)
LEDs = []
for plus_LED_id in range(LED_count):
LEDs.append(machine.Pin(plus_LED_id + start_LED_GPIO, machine.Pin.OUT))
pass_code = [buttons[0], buttons[2], buttons[1]]
last_deci_val = 0
last_button_state = 0
print(f'Selected output: {LED_selected_colour[last_deci_val]} ({last_deci_val})')
while True:
#
deci_val = 0
for sel_val_one in range(sel_states): #0 then 1
s0.value(sel_val_one)
for sel_val_two in range(sel_states):
s1.value(sel_val_two)
sleep(0.02)
deci_val += (pow(2, sel_val_one + 2 * sel_val_two) * mux_in.value())
sleep(0.05)
if last_deci_val != deci_val:
last_deci_val = deci_val
if 0 <= last_deci_val < 9:
print(f'Selected output: {LED_selected_colour[last_deci_val]} ({last_deci_val})')
else:
print(f'Selected output: {last_deci_val}')
print('This output is outside of the LEDs range (0-8), so inserting the passcode will do nothing.')
if len(key_presses) >= button_count:
if 0 <= last_deci_val < 9:
if key_presses[:button_count] == pass_code:
print('Correct passcode')
print(f'Toggling {LED_selected_colour[last_deci_val]} ({last_deci_val})')
LEDs[last_deci_val].toggle()
else:
print('Wrong passcode')
else:
print('The output is outside of the LEDs range (0-8), doing nothing.')
key_presses = key_presses[button_count:]
if __name__ == "__main__":
main()