
Lesson 6
PLC Program Structure: Jumps, Functions (FC) and Function Blocks (FB)
Jumps and labels, why a skipped rung is not paused, functions without memory, function blocks with instance data, and a full motor starter block.
From Usta's field manual in Meridian Works, a story-driven PLC course: chapter 6, “Structure”. Choosing which code runs, and writing a job only once.
One program, eight times
There are three hundred and forty rungs in one block. No sections. No comments after page four. There are eight motor starters in a row, and they are all almost the same.
The whole problem is in that word "almost".
On the day they were written, all eight were the same. The man who wrote the program had one starter that worked. He copied it seven times, changed the addresses and went home. That was not the mistake. The mistake came later, and it grew a little with every repair.
The extract fan tripped for nothing one cold morning. Somebody stretched its alarm delay from two seconds to five. The mixer got an interlock after the business with the guard door. Motor six was moved to a different overload contact. The old address stayed on the rung too, just in case. Every one of these changes was correct. Each was made by somebody who knew the job, at that machine.
None of them reached the other seven copies.
So there is no longer one "motor starter logic" in this plant. There are eight separate programs. They are so alike that nobody reads them carefully. But they are different enough for one of them to be wrong. You cannot find the wrong one by searching either. The fault is not a wrong contact; it is a missing one. A missing contact leaves no trace on the page.
That is the real price of copy-paste. A repair does not travel to the other copies. Every repair pushes the copies a little further apart. A program does not rot because it is long. It rots because there is no single place left where the truth is written.
There are two separate diseases in this drawer. This chapter gives you a tool for each.
Everything runs every scan, needed or not. The manual jog rungs are scanned even when the plant is in automatic and nobody is near the panel. That is what a jump is for. You choose which section of the program runs this scan.
Everything is written as many times as it is used. That is what a block is for. You write the logic once and call it from wherever it is needed. If the block has to remember something, each use gets its own memory.
You will do three jobs in this room. First, a mode switch that stops the manual and automatic sections fighting over one belt. Then three fans run from one starter block. Last, a star-delta starter written once and used on two pumps.
Copy-paste kills a plant.
Jumps and labels
A label is a name given to a rung. It does nothing itself; it is a mark on the page. In TIA Portal it is called LABEL and sits at the start of the target network. In Studio 5000 it is called LBL and must be the first instruction on the rung. Two labels in the same block, or in Rockwell the same routine, cannot have the same name. The rest of the rung is ordinary ladder and runs normally.
A jump (JMP) carries the name of a label and is conditional. When its rung is true, the processor stops working down the page. It carries on from the rung with that label. The rungs in between do not run. They are not deferred and not queued. For that scan they are as good as not there.
That is the whole instruction. What matters is the consequences.
Do not put a coil after a jump on the same rung. If the rung is true, the jump fires and the coil is skipped. If the rung is false, the jump does not fire, but the coil is on a false rung. There is no third case. So that coil can never energise. The editor lets you draw it, but it will not work. A jump sits at the end of its rung, alone. TIA already draws JMP like a coil at the end of the rung.
A jump cannot leave its block. Labels are local. In Siemens they are valid within the block, in Rockwell within the routine. A JMP in one block cannot see a label in another. That is a good thing. A program that can jump anywhere cannot be read or tested.
A jump backwards is possible, and it is how you hang a CPU. Nothing stops you jumping to a label higher up and making a loop. Only you can write the way out. If the loop never ends, the scan watchdog steps in. A Siemens CPU eventually goes to STOP. A Rockwell controller raises a major fault. Either way the plant stops. Always jump forwards. If you want something repeated, wait for the next scan.
The real place for jumps is mutually exclusive sections.
A plant in automatic must not listen to the jog buttons. A plant in manual must not run the sequence. These are not two conditions to add to a hundred rungs. They are two modes. The program has two sections, and only one of them runs each scan:
rung 12 Mode_Auto → JMP AUTO
... the manual section ...
JMP DONE
LBL AUTO
... the automatic section ...
LBL DONE
Read it once and it is clear. The other way is to put a Mode_Auto contact at the head of every rung in both sections. That is thirty extra contacts. On some tired evening one of them will be left off.
Three habits keep jumps safe:
- Jump forwards, over a whole section. Never into the middle of one.
- Name the label after the section it heads:
AUTO,MANUAL,DONE. A label calledL1tells nobody anything. - Do not jump to save scan time. This processor gets through three hundred rungs in far less than a millisecond. A few microseconds are not worth a structure nobody can follow.
You will build exactly this in the Control Room's first work order. Read the next page first. The most dangerous mistake with jumps is there.
Skipped is not paused
The sentence to take away from this chapter is this: skipped code is not paused code. That code never ran. The machine carried on anyway. Two things follow, and both have stopped plants.
One. A skipped rung cannot turn its own output off.
Remember the scan from Chapter One. At the end of every scan the processor writes the output image to the cards. It does not check whether any rung touched that bit this scan. The bit holds the last value written to it. Even if no rung writes it, the contactor gets that value.
Picture it. The jog button is held and the belt is running. While it runs, the selector is turned to AUTO. Now the jump fires and the jog rung is not scanned. Nobody writes FALSE to Conveyor. The belt keeps running. No fault, no lamp, no line in the diagnostics. As far as the processor is concerned all is well, because you asked for that rung not to run.
The cure is a discipline, not an instruction: every output one section can leave on, the other section writes too. Chapter One said "each coil is written in one place". Jumps are the one exception to that rule. Only one of two mutually exclusive sections runs each scan, so the same coil can stand in both. If Conveyor is driven from both sections, both must write it with a plain coil. An output that only one section writes must be cleared by the other. There is a better way. Each section writes its own request bit: Jog_Run and Auto_Run. Outside the skipped region, one rung scanned every scan drives the contactor from those two bits. The deciding rung is never skipped, so a mode change cannot leave anything running.
Two. A skipped timer does not know it slept.
Chapter Three said it: time is measured, not counted. A timer does not add ten milliseconds each scan. It reads the clock. It subtracts the reading from the last time this instruction ran. It adds the difference. That is what keeps timing right when the scan time changes. It is also what makes a skipped timer dangerous.
These numbers come from this machine. A TON with a ten-second preset runs normally and reaches 0.50 s. Then its section is skipped for two seconds. The elapsed time stays where it is, because nothing runs the instruction. Then the mode comes back and the rung is scanned once. The timer reads the clock and sees 2.01 s since it last ran. It adds it all in one step and goes to 2.51 s.
Now apply that to a start horn. The horn timer is a three-second TON. The plant sits in manual for ten seconds with the automatic section skipped. The operator turns the selector. The automatic section is scanned for the first time and the horn timer reads ten seconds at once. Its time is already up. The conveyor starts, and the horn never sounds. Somebody may be standing at the head of the belt.
The rule: do not jump over timing logic.
If a timer must wait, hold it with a contact, not with a jump. A TON whose input is FALSE resets every scan and re-reads the clock. That is what makes it start correctly when the plant needs it. A timer scanned every scan can be trusted. A timer that is never scanned is a mine that will go off one day.
But in a mode switch the automatic section has timers of its own, and that section is skipped. Then one cure is left. The timer's input must be FALSE on the scan you come back. Then the timer resets and the skipped seconds are lost. What the input was before the skipping does not matter. That scan does not come by itself. If the selector drives the input directly, the input is already TRUE on the scan you come back. If a request bit drives the input, clear that request in the other section on the way out. You will do exactly this in the Control Room's first work order. Where you have the choice, keep the timer outside the skipped section.
One last trap: counters do not leap, they under-count. A counter only sees its rung's rising edge while that rung runs. If twelve jars pass while the rung is skipped, those counts do not arrive late. They never arrive. When the rung comes back it sees at most one edge and adds one. The total does not look wrong afterwards. That is exactly the problem.
The processor did what it was told and did not run that rung. It does not know what the rung was for.
Functions: work without memory
A function is a piece of logic you call by name. You give it values, it does its work and gives values back. It keeps nothing. In Siemens it is an FC. In Rockwell the closest match is a subroutine. You call it with JSR. The subroutine takes its parameters with SBR and hands them back with RET.
The function's interface is the list of values going in and coming out. For example Raw and Full_Scale in, Percent out. In the body these names are used like ordinary symbols: a contact on Enable, a coil on Valid, a MOVE into Percent. The body writes no addresses. A block with a fixed input address inside it is copy-paste in disguise.
In this simulator a call runs in four steps:
- A small scratch area is set aside for the call. The area is cleared to zero.
- The arguments are copied from the caller's symbols into this area.
- The body runs from top to bottom. Every rung inside the block starts fresh from the left rail. The conditions on the calling rung do not carry in. The calling rung decides whether the call happens. The block decides what happens inside.
- The declared outputs are copied back to the symbols wired to them at the call site.
Four rules follow. The editor enforces the first two.
Every input must be supplied. A missing input is a hole. The editor refuses the call rather than pass a random value. An output may be left unwired. Calculating a result nobody uses does no harm.
An FC has no instance data. So an FC call names no instance. An FC cannot declare static variables either, because it has nowhere to keep them. If you need one, you actually need a function block. The next page is for that.
Do not rely on an output you did not write. This simulator clears the scratch area at every call. An unwritten output comes back as zero here. Real CPUs differ. Siemens does not guarantee the value of an unwritten FC output. In Rockwell the tags a subroutine uses are retained, and the value from the previous call is still there. Do not rely on any of these behaviours. The rule is the same on both platforms: write every output on every path. Write it on the path where nothing happens too. Zero is a value, and it should be one you chose.
Edge memory inside a function is shared. This is a real trap.
A P or N contact keeps the operand's value from the previous scan in a hidden bit. A function has no memory of its own, so that bit is set aside once for the compiled body. Every call uses the same body and the same bit. Two calls, one edge memory. Rockwell has the same trap. The storage bit of a ONS in a subroutine is an ordinary tag. If you call the subroutine from several places, they all use the same bit.
The fault shows up two ways. If both operands are TRUE, the first call takes the edge. The second call finds the bit already TRUE, and its pulse never happens. If the operands differ, the bit changes twice every scan. The pulse comes every scan and is no longer a pulse. Which one you see depends on what the other machine is doing at that moment. The editor warns you when you draw this. Take the warning seriously. If reusable logic needs an edge, it needs a function block.
An FC suits work that is a calculation. The same inputs give the same result every scan:
- turning raw card counts into degrees,
- clamping a value between two limits,
- turning litres into kilograms with this product's density,
- a lamp test pattern or a checksum.
There is no "yesterday" in these jobs.
A function is a spanner. It does not remember the last bolt.
Function blocks and instance data
A function block is a function that is allowed to remember. In Siemens it is an FB. In Rockwell the match is an Add-On Instruction, an AOI for short. The way it remembers is the most useful idea in this manual.
The block is the recipe. The instance data is the pot.
The recipe is written once: soften the onions, add the rice, cover, cook twenty minutes. There are no onions in the recipe. You can cook it in three pots at once. Pot two being ten minutes behind pot one is not a contradiction. It happens in every kitchen every day.
The mechanism is simple. The body is compiled once. The body reaches its interface members by position, not by a fixed address: "the fourth byte of the area I was given". Each call brings that area, the instance data, with it. Same instructions, different area, different memory. That is the whole trick. It is also why a block that reaches out to a global tag breaks. That rung has a fixed address in it, and all three instances write the same bit.
The two platforms name the instance data differently:
- In Siemens each FB call gets an instance DB. If an FB is called from inside another FB, its data can live inside the caller. That is called a multi-instance.
- In Rockwell you create a separate tag of the AOI's type for each use. That is the backing tag. An AOI can carry another AOI as one of its own local tags.
The instance data holds:
- the inputs, copied in at the call,
- the outputs, copied out when the body finishes,
- the statics, the things the block remembers between calls: a seal-in bit, a total, a step number. In Rockwell these are the AOI's local tags.
- each timer declared in the interface, with its own preset, its own elapsed time and a record of when it last ran,
- the hidden memory bit of every edge instruction in the body.
The last two are the ones people forget most. They are exactly what an FC cannot give you.
Look at an example with three fans. The alarm delay is two seconds. Fan 1 trips at t = 0. Fan 2 trips half a second later. Fan 3 does not trip. Fan 1's lamp lights at 2.0 s and fan 2's at 2.5 s. Each lights two seconds after its own trip. Fan 3's elapsed time stays at zero. Each call ran the same TON instruction on a different memory. Had they shared one timer, fan 2's lamp would have lit at 2.0 s. And you would have spent a week blaming the overload relay.
Keep three things in mind.
An FB call must name its instance data. No instance data, no call. Give it instance data that belongs to another block and the editor refuses. Each instance data has the shape of one block. An AOI is the same: the backing tag must be of that AOI's type.
Never give two calls the same instance data. It compiles and shows no error. But the result is two motors sharing one seal-in bit and one alarm timer. Each writes over the other's outputs. The behaviour is so strange that people replace contactors over it. Use one instance data for each device on site. Let the names say which device: Fan1_Data, Fan2_Data, Fan3_Data.
The instance data is your window into the block. It is real, named memory, so you can watch it from outside while the plant runs: Fan2_Data.Latch, Fan2_Data.Alarm, Fan2_Data.T_Alarm.ACC. In Rockwell you can also open the AOI's logic in the context of one backing tag (data context). When a motor will not start and the panel says nothing, that is where you look. Half of commissioning is this.
One more warning that belongs with page three. On a false rung, the block's body does not run. A block that does not run does not change its outputs, and they keep their last values. Put a stop button in front of a starter call and the block never sees the stop. The motor keeps turning until the rung is true again. A skipped block is not a stopped block. Call your blocks unconditionally. If you do otherwise, you should be able to say why. Let the logic inside the block decide what to do.
You will build the starter itself in the next work order: one block, three fans, three instance data. Read the next page first. The interface decides how that job turns out.
The motor starter, in full
Every plant in the world runs on this block. Learn it well here. You will write it again in some form for the rest of your working life.
| Section | Member | Type | What it means |
|---|---|---|---|
| IN | Start |
BOOL | momentary start command |
| IN | Stop |
BOOL | TRUE while the stop button is not pressed |
| IN | Fault |
BOOL | motor protection has tripped |
| OUT | Running |
BOOL | contactor command |
| OUT | Alarm |
BOOL | the fault has lasted long enough to be real |
| STAT | Latch |
BOOL | this motor's seal-in memory |
| STAT | T_Alarm |
TIMER | this motor's own alarm delay |
The STAT section in Siemens is the AOI's local tags in Rockwell. Read the lines one by one, slowly. Every line is a decision.
Start is an event. A button is a command, not a state. You saw this in Chapter Two. The block's job is to turn a short press into a lasting state. That is the seal-in you have written since the Gatehouse: run if the button was pressed or it is already latched, and hold while the permissives are good. The memory that makes it last is Latch. Latch is a static, because it must survive from one scan to the next. And fan 2's latch concerns only fan 2.
Stop is a permission. This is the line people get wrong most. It means: TRUE while the button is not pressed. The parameter does not say "stop". It says "you may run".
The reason is in the field. A stop button is wired NC. Pressing it opens the circuit. While all is well the input is energised. Pressing the button cuts the power. So does a broken wire, a loose terminal or a corroded contact. All of these produce a 0, and 0 means "stop". The safe state is the de-energised state. That safety reaches inside the block only if the parameter carries the same meaning as the wire.
Invert the meaning at the interface, for example by passing "Stop_Pressed", and you build a machine that keeps running when its stop button falls off. Do not be clever here. Inside the block this parameter is a permissive in series with the seal-in. No permission, no latch.
Fault is a state, and it wants a timer. A motor protection contact chatters. It opens and closes on a hard start. It twitches when the panel door slams. A lamp that lights for forty milliseconds teaches operators to ignore lamps. So the block does not report every fault. It reports a fault that has lasted two seconds. The TON's input is the fault condition. The power flow after the box is your answer. That timer is a static too. So each motor times its own fault.
Running and Alarm are outputs. They are copied to whatever the call site wired: F1_Run on one call, F2_Run on the next. Notice what is not in the interface. No addresses, no fan numbers. A block that knows which fan it is, is not a block.
Two more things.
Statics are part of the interface too. Latch and T_Alarm are not parameters, and you cannot give them values at the call. They are still declared in the interface, because they define what the block is: a starter that keeps its own memory. That declaration sets the size of the instance data. That is why Fan3_Data takes up real space in the CPU.
The interface is a contract. Once there are three calls, changing a parameter changes three call sites. On a real plant that means three calls in two programs and a document somebody printed. Add new parameters at the end. Never give an old parameter a new meaning. And fill in the comment column while you still remember why. The line Stop — TRUE while the stop button is NOT pressed (NC) has saved many motors.
A block that has to be told which motor it is has not been written yet. It has been copied.
FC or FB? One question
You do not need a philosophy. Ask one question before you create the block:
Does this block have to remember anything between calls?
If no, it is a function: an FC in Siemens, a subroutine in Rockwell. If yes, it is a function block with instance data: an FB in Siemens, an AOI in Rockwell.
But "remember" is wider than it looks. All of these are memory, and every one of them takes you to an FB:
a seal-in bit · any timer · a counter · an edge (P, N or ONS) · the previous value of anything · a step number · an alarm that stays latched until acknowledged · an accumulated total · a filtered average · "was this the first fault?"
If your block has any of them, the answer is settled. A timer counts twice. It is memory, and its elapsed time must be separate for each call. Otherwise two calls see each other's seconds.
| The job | Remembers? | Block |
|---|---|---|
| Scale raw counts to °C | no | FC |
| Clamp a value between two limits | no | FC |
| Litres → kilograms for this product | no | FC |
| Build a lamp pattern from a word | no | FC |
| Motor starter with seal-in | yes — Latch |
FB |
| Star-delta with a timed transition | yes — two timers | FB |
| Debounce a chattering sensor | yes — a timer | FB |
| Runtime hour meter with service alert | yes — an RTO | FB |
| Alarm with acknowledge and first-out | yes — latches | FB |
| Valve with travel timeout and fault | yes — timer and latch | FB |
Look at the right-hand column on a real plant: nearly all of it is FB. That is not laziness. Machines are made of things that are in a state. Everything in a state has a memory somewhere.
If you are not sure, take the FB. An unnecessary FB costs a few bytes of instance data per call. A wrong FC costs a shared timer and a shared edge. That fault only shows when two machines run at once. That is, on the plant's busiest day, in front of the customer.
But do not reach for an FB out of habit. A well-written function has no history, and that is a guarantee. The same inputs always give the same answer. So a function is easy to test at the bench. It can be called safely from three places. It cannot fall into a strange state. Where a calculation will do, use a calculation.
There is a third answer: no block at all.
Logic that appears once in the program, and always will, is clearer as rungs in the main program. A block called from one place, with nine parameters and a name like Handle_Line_Stuff, is not reuse. It is the same logic with one more door in front of it. The next person now has to look in two places. The test is simple: would you call it twice? If the answer is no and will stay no, leave the logic where it is.
The last job in this room is the cleanest example of the rule. A star-delta starter runs the motor up in star and waits. Then it opens the star contactor and waits again. That second wait is a dead time. The arc must go out before the delta contactor closes. Then delta closes. That is two timers and a latch per motor. And it is needed on two motors. Ask the question. The answer will not take long.
Ask before you build the block. Turning an FC into an FB later means changing every call site one by one. One of them is always in a program you have never opened.
Program hygiene
Blocks alone do not make a program good. A badly organised program with blocks in it is a bad program with more places to hide. Boring rules make a good program. They are all here.
Names. A block name says what the thing is: Motor_Starter, Star_Delta, Scale_Analog. An instance name says which one: Fan2_Data, Pump1_Data. A parameter name says what the value means, not where it comes from. Stop, not I0_1. Fault, not Terminal_14. Only the call site should know where the wire lands.
One block, one job. If you cannot say what a block does in one sentence without "and", it is two blocks. Motor_Starter starts and stops a motor. It does not count running hours. It does not drive the HMI lamp. It does not decide the sequence. Those are other blocks' jobs.
Write the explanation where people look. With the line down, nobody opens a separate document. Everybody sees the interface, because it is on the screen when the block opens. The comment column is the only documentation that gets read. It is the one place worth the effort.
The main program shows the order of things. It should read like a table of contents:
condition the inputs (filter, scale, debounce)
decide (modes, sequence, interlocks)
act (call the starters, the valves, the drives)
report (alarms, lamps, HMI values)
Order matters a lot here. It is all one scan, and the scan runs downwards. If a block reads a value written by a block called below it, it gets last scan's value. That value is ten milliseconds old. Usually that is harmless. Sometimes it costs you an afternoon: an interlock that clears one scan late, a lamp that flickers, a sequence that skips a step at one speed only. Data should flow downwards through the main program. Where it cannot, know it and write it in the rung comment.
Do not nest blocks deeply. A block calling a block that calls another is fine. This simulator allows sixteen levels and faults beyond that. Real CPUs have a limit too. Three levels is plenty. Every level is one more block for the person following a signal to its end. That person is usually doing it with a torch in one hand.
Comment every rung. Do not write what it does; the ladder already shows that. Write why: horn must sound before the belt moves — site rule after the 2019 incident. The rung shows how. Only you can leave the why behind.
There is one test:
Could somebody who has never seen this plant open your program at three in the morning, with the line down, and find the fault?
They do not need to admire it. They need to find the fault, fix it and go home. Everything in this chapter exists to make the answer yes: sections that skip cleanly, a block written once, instance data that says which fan, an interface with its comments filled in.
Two people wrote programs in this building. One wrote knowing a stranger would read it one day. The other thought nobody would. He was right until the morning he did not come in. You have read both programs. You know which one still stands.
You are not writing this for the machine. The machine accepts anything. You are writing it for the person after you. One day, on another plant, that person will be you.