Skip to content

Lesson 8: Branches and OR Logic

The Python instinct

if auto_mode and state == "sorting" and is_large:
    diverter = True
elif manual_mode and diverter_button:
    diverter = True

The ladder logic way

Ladder logic has two ways to combine conditions. Commas inside rung(...) are implicit AND. For OR, use Or():

from pyrung import Bool, Int, Program, rung, branch, comment, out, latch, reset, Or, And

Auto          = Bool()
Manual        = Bool()
StopCircuitOK = Bool()     # NC stop circuit: True when healthy
StartBtn      = Bool()
EstopOK       = Bool()     # NC safety relay permission
Running       = Bool()
Light         = Bool()
DiverterBtn   = Bool()
DiverterCmd   = Bool()
ConveyorMotor = Bool()
StatusLight   = Bool()
Mode          = Int()

with Program() as logic:
    # Motor runs in either mode when started
    with rung(Or(Auto, Manual)):
        out(Light)                        # Status light: either mode is active

    # Or works with comparisons and any number of conditions
    with rung(Or(Mode == 1, Mode == 3, Mode == 5)):
        latch(Running)

Or is variadic, so you can pass any number of conditions. And is the explicit form of comma-separated conditions, useful inside Or for nested groups. Or and And mirror any([a, b, c]) and all([a, b, c]) in Python.

Branches

A branch creates a parallel path within a rung. Think of it as a second wire that ANDs its condition with the parent's.

Here's the conveyor's motor rung. EstopOK gates everything. It's a permission input from the safety relay, True when the world is safe to run. Below that, the motor and status light share the same gate:

  EstopOK (parent rung — True when safe)
      +-- Running -> out(ConveyorMotor)
      +-- Running -> out(StatusLight)
with Program() as logic:
    comment("Start/stop - NC stop resets when pressed or wire broken")
    with rung(StartBtn, Or(Auto, Manual)):
        latch(Running)
    with rung(~StopCircuitOK):
        reset(Running)
    with rung(~EstopOK):
        reset(Running)

    comment("Motor output - EstopOK gates all outputs")
    with rung(EstopOK):
        with branch(Running):
            out(ConveyorMotor)
        with branch(Running):
            out(StatusLight)

This is the gate pattern. The parent rung holds your master condition, and every branch inside inherits that permission automatically. Lose the gate, lose all the outputs, atomically, in one scan. EstopOK reads as "safety is satisfied" so the gate uses the raw tag with no ~. The reset rungs use ~StopCircuitOK and ~EstopOK because those fire when the NC circuits open. That's the same ~ convention from Lesson 3.

The gate pattern is the textbook ladder structure for any permission or interlock, such as guard doors, light curtains, and machine-enabled flags. Real fail-safe E-stop wiring lives in Lesson 11. Here, the gate is general-purpose.

Combining branches and Or

The diverter needs to fire in two cases: auto mode during sorting, or manual mode with the button pressed. That's Or with And, the same pattern as any([all([...]), all([...]]) in Python:

    comment("Diverter output - auto sort OR manual button, gated by EstopOK")
    with rung(
        EstopOK,
        Or(
            And(State == SORTING, IsLarge, Auto),
            And(Manual, DiverterBtn),
        ),
    ):
        out(DiverterCmd)

The diverter rung reads State and IsLarge directly from the state machine in Lesson 7. No intermediate latch is needed. Both control sources combine into one rung with a single out(DiverterCmd). Remember "order has meaning" from Lesson 1? This is how you escape it: one coil, one rung. If two separate rungs both out the same tag, the last one evaluated wins. A false manual rung below a true auto rung would de-energize the diverter. Put every reason the output should energize into one rung, and order stops being a side effect.

Key concept: order inside a rung

A rung is commonly said to be evaluated left to right, top to bottom. It's a little more nuanced than that. Instructions run in the order written. The rung's own condition is read once and holds for everything below it. A branch reads its own condition when execution reaches it, so it sees what the instructions above it in the same rung just wrote. Order inside a rung has meaning, just as order between rungs does (Lesson 1's scan cycle). The scan is still deterministic, so Testing can pin it down. When a branch should not depend on a write above it, read the tag on the rung's own condition or move the write to a rung of its own.

Seal-in: a branch that holds itself

Lesson 3 used latch/reset for start/stop control. The classic ladder alternative is a seal-in, a single rung where the output feeds back into its own branch:

with rung(~StopCircuitOK):
    with branch(Or(StartBtn, Running)):
        out(Running)

Running appears in its own branch condition. Press StartBtn and Running energizes. Release StartBtn and Running still powers the branch, so Running holds itself in. Open the stop circuit and StopCircuitOK goes False, so the parent rung drops and breaks the seal. Reach for latch/reset when clarity matters. Expect seal-in in every legacy ladder you inherit.

Try it

from pyrung import PLC

with PLC(logic) as plc:
    StopCircuitOK.value = True       # Stop circuit is healthy
    EstopOK.value = True

    Auto.value = True
    StartBtn.value = True
    plc.step()
    assert Running.value is True
    assert ConveyorMotor.value is True
    assert StatusLight.value is True

    StartBtn.value = False
    plc.step()
    assert Running.value is True     # Still running (latched)

    # E-stop kills everything (NC opens)
    EstopOK.value = False
    plc.step()
    assert ConveyorMotor.value is False
    assert StatusLight.value is False
    assert Running.value is False

Exercise

Add a ManualLight that is on only in manual mode. Write a test that switches from Auto to Manual mid-run and verifies the diverter control source changes without the motor stopping. Test that the diverter button does nothing in auto mode.


Each bin has a count, the diverter has a state, and there's a mode selector. That's a lot of scattered tags. In a real PLC, you'd group them into structures (UDTs) for the bins and the equipment.

Also known as...

OR is a parallel branch of contacts. AND is contacts in series. branch() is "parallel branch" everywhere. The safety-gate pattern is sometimes called "Master Control Reset" (MCR). Seal-in is the classic OR-branch with a series stop contact.