Subroutines: structuring a program somebody else can read
Splitting a program into routines is the cheapest readability improvement available, and there are two traps.
Short answer
A jump-to-subroutine instruction calls another routine, which runs to completion and returns to the next rung. Routines are how a program becomes navigable rather than one enormous ladder. The two traps are that a routine which is never called looks exactly like logic that does not work, and that outputs in an uncalled routine hold their last value.
A five thousand rung program in one routine is unreadable regardless of how good the individual rungs are. Splitting it is the cheapest improvement available.
How the call works
The jump-to-subroutine instruction transfers execution to another routine. That routine solves to its end, then execution returns to the rung after the call.
It is a call, not a jump. The program comes back.
Trap one: a routine nobody calls
Logic that is never executed looks identical to logic that does not work. The rungs are there, they read correctly, and nothing happens.
When a section of a program appears to be ignored, check that it is being called before reading a single rung of it.
Trap two: outputs freeze rather than clear
A routine that stops being called does not turn its outputs off. Nothing solves the rungs, so the coils hold whatever value they had.
For conditionally called routines this matters enormously, and the usual fix is to clear the relevant outputs before the conditional call rather than relying on the routine to do it.
A structure that works
One routine per machine area, plus separate routines for alarms, manual mode and analog handling. Somebody looking for a specific behaviour should be able to guess which routine it is in.
Common questions
- What happens to outputs in a routine that is not called?
- They hold their last value. The rungs are not solved, so nothing updates them, and a coil that was energised when the routine stopped being called stays energised. This is a genuine trap when routines are called conditionally.
- How should I split a PLC program into routines?
- By machine area or by function, so that a person looking for a specific behaviour knows where to look. One routine per station, plus separate routines for alarms, for manual mode and for analog handling, is a structure most engineers can navigate without a map.
Keep reading
- Safety
SIL or PL: which one does your machine need?
Two standards, two scales, and one machine. Which one applies, how they map to each other, and why the answer is usually ISO 13849.
- Safety
Categories B, 1, 2, 3 and 4, in plain terms
Five architectures, what a single fault does to each, and the practical wiring that goes with them.
- Safety
Safety relay or safety PLC: how to decide
One is a wiring decision, the other is a programming one. The count of safety functions, not the size of the machine, is what settles it.