print("Este é o programa 'Semáforo'.")
from machine import Pin
from time import ticks_ms, sleep

# Definir os LEDS
led_red = Pin(21, Pin.OUT)
led_yel = Pin(22, Pin.OUT)
led_gre = Pin(19, Pin.OUT)

# Definir o botão
Bp = Pin(23, Pin.IN) #Azul
Bi = Pin(18, Pin.IN) #Rosa


def intermitente():

    global bival

    led_gre.value(0)
    led_red.value(0)
    led_yel.value(1)

    last = ticks_ms()
    bival = False
    while True:
        now = ticks_ms()

        if now - last >= 1000:
            led_yel.value(not led_yel.value())
            last = ticks_ms()

        if not Bi.value():
            bival = True

        if Bi.value() and bival:
            led_yel.value(0)
            bival = False
            normal()


def normal():

    global bival

    last = ticks_ms()

    while True:
        
        led_gre.value(1)
        bpvar = False
        while True:
            now = ticks_ms()

            if not Bp.value():
                bpvar = True

            if bpvar and now - last >= 4000:
                led_gre.value(0)
                last = ticks_ms()
                break

            if now - last >= 9000:
                led_gre.value(0)
                last = ticks_ms()
                break

            if not Bi.value():
                bival = True

            if Bi.value() and bival:
                bival = False
                intermitente()
        
        led_yel.value(1)
        while True:
            now = ticks_ms()
            if now - last >= 1000:
                led_yel.value(0)
                last = ticks_ms()
                break

            if not Bi.value():
                bival = True

            if Bi.value() and bival:
                bival = False
                intermitente()

        led_red.value(1)
        while True:
            now = ticks_ms()
            if now - last >= 5000:
                led_red.value(0)
                last = ticks_ms()
                break
            
            if not Bi.value():
                bival = True

            if Bi.value() and bival:
                bival = False
                intermitente()

bival = False
normal()