# mPy - shuttle with 2 x 3 2-aspect signals and 5 IR train detectors
#    signals set by detectors IRQ
# by Anthony Vogelaar, Perth Scotland
# rev 0.10  2024-11-03  initial release

from	machine_sim	import	Pin
import	time

# =============================== local ===================================

last_irq    = None

# save triggered irq object
def onSensor(sender):
    global last_irq

    last_irq = sender


# wait, return when sensor triggered
def wait(sensor):
    global last_irq

    i = 0
    while True:
        if last_irq:
            ir = last_irq
            last_irq = None
            if ir == sensor: break
        time.sleep(0.1)
        Pin.qtExe()				                # background task - GPIO simulator
        i += 1
        if i % 10 == 0:
            print('*', end='', flush=True)

# =========================== Hardware set-up =============================

RED   = 0
GREEN = 1

pin_pa0  = 16									# pin numbers on Esp32s2 for signal pa0
pin_pa1  = 18
pin_pa2  = 33
pin_pb0  = 35
pin_pb1  = 37
pin_pb2  = 39

pin_ir0  = 17                                   # pin numbers on Esp32s2 fot IR sensor 0
pin_ir1  = 10
pin_ir2  =  8
pin_ir3  =  6
pin_ir4  =  4

signal_a0  = Pin(pin_pa0, Pin.OUT, value=RED)	# instantiate signal output objects in RED
signal_a1  = Pin(pin_pa1, Pin.OUT, value=RED)
signal_a2  = Pin(pin_pa2, Pin.OUT, value=RED)
signal_b0  = Pin(pin_pb0, Pin.OUT, value=RED)
signal_b1  = Pin(pin_pb1, Pin.OUT, value=RED)
signal_b2  = Pin(pin_pb2, Pin.OUT, value=RED)

sensor_ir0 = Pin(pin_ir0, Pin.IN, Pin.PULL_UP)  # instantiate sensor input objects
sensor_ir1 = Pin(pin_ir1, Pin.IN, Pin.PULL_UP)
sensor_ir2 = Pin(pin_ir2, Pin.IN, Pin.PULL_UP)
sensor_ir3 = Pin(pin_ir3, Pin.IN, Pin.PULL_UP)
sensor_ir4 = Pin(pin_ir4, Pin.IN, Pin.PULL_UP)

sensor_ir0.irq(onSensor, Pin.IRQ_FALLING)       # enable sensor IRQ calling onSensor
sensor_ir1.irq(onSensor, Pin.IRQ_FALLING)
sensor_ir2.irq(onSensor, Pin.IRQ_FALLING)
sensor_ir3.irq(onSensor, Pin.IRQ_FALLING)
sensor_ir4.irq(onSensor, Pin.IRQ_FALLING)

# ============================== main ====================================
 
while True:
    signal_a0.value(GREEN)						# train departs A
    signal_a1.value(GREEN)
    signal_a2.value(GREEN)
    wait(sensor_ir1)
    signal_a0.value(RED)						# train passes A0
    wait(sensor_ir2)
    signal_a1.value(RED)						# train passes A1
    wait(sensor_ir3)
    signal_a2.value(RED)						# train passes A2, arrives in B
    wait(sensor_ir4)
    signal_b0.value(GREEN)						# train departs B
    signal_b1.value(GREEN)
    signal_b2.value(GREEN)
    wait(sensor_ir3)
    signal_b0.value(RED)						# train passes B0
    wait(sensor_ir2)
    signal_b1.value(RED)						# train passes B1
    wait(sensor_ir1)
    signal_b2.value(RED)						# train passes B2, arrives in A
    wait(sensor_ir0)

# ================================ end ================================
