from machine import Pin
import utime
# initialize pins
push_button = Pin(21, Pin.IN, Pin.PULL_DOWN)
red = Pin(2, Pin.OUT)
yellow = Pin(1, Pin.OUT)
green = Pin(0, Pin.OUT)
# initial values
red.value(0)
yellow.value(0)
green.value(0)
lastInterruptTime = 0
# debounce function so the interrupt handler is activated once per button push
# note: not necessary if 'bounce' setting on push button is not checked
def debounce():
# print("CHECK BOUNCE")
global lastInterruptTime
currentTime = utime.ticks_ms() # get current time in ms
if currentTime - lastInterruptTime < 400: # find difference in time between current and last interrupt time, check if less than 400ms
return False
lastInterruptTime = currentTime
return True # ready to be used again!
def push_button_interrupt_handler(pin):
if debounce(): # check that debounce returns true so the logic is ready to be run
print("Interrupt detected..." + str(pin))
if ((green.value() == 0 and yellow.value() == 0 and red.value() == 0) or (green.value() == 0 and red.value() == 1)): # conditions for green to be toggled on
print("GREEN LIGHT")
green.toggle()
if (red.value() == 1):
red.toggle()
elif (green.value() == 1 and yellow.value() == 0): # conditions for yellow to be toggled on and green to be toggled off
print("YELLOW LIGHT")
green.toggle()
yellow.toggle()
elif (yellow.value() == 1 and red.value() == 0): # conditions for red to be toggled on and yellow to be toggled off
print("RED LIGHT")
yellow.toggle()
red.toggle()
utime.sleep_ms(200)
# calls button interrupt handler on rising edge of button signal
push_button.irq(trigger = Pin.IRQ_RISING, handler = push_button_interrupt_handler)