Math (output instruction)

SUB: Subtract

Writes A minus B into the destination.

Also called: minus, difference.

SUB(number, a, b, real)

Arguments

NameWhat it isAcceptsDefault
destinationWhat the instruction acts ona registerrequired
aValue Aa number or a tag0
bValue Ba number or a tag1
realFloating pointtrue or falsefalse

Arguments are positional and this table is generated from the simulator's own instruction registry, so it always matches what the engine accepts.

What it does

SUB writes the first value minus the second into its destination, every scan its rung is true. The two everyday jobs are how much is left, which is target minus actual, and how far off are we, which is measured minus wanted.

The second of those is worth naming, because deviation is the basis of most alarming. Once the difference between where a process is and where it should be exists as a number, a compare on it gives you a deviation alarm, and an on-delay timer in front of the alarm stops it nuisance tripping on a transient.

Results are whole numbers unless floating point is switched on for the instruction, so any fraction is truncated, and they are held in 32 bits, which is roughly plus or minus two thousand million.

A rung you can run

How many to go, and how far off

RUNG 1SUB Parts_RemainingBatch_Ta… − Parts_Ma…RUNG 2Parts_Remaining< 1Batch_CompleteRUNG 3SUB Fill_ErrorFill_Act… − Fill_Tar…RUNG 4ABS Fill_DeviationABS Fill_Err…RUNG 5Fill_Deviation> 25Fill_Out_Of_Spec
SUB(Parts_Remaining,Batch_Target,Parts_Made)
LES(Parts_Remaining,1)OTE(Batch_Complete)
SUB(Fill_Error,Fill_Actual,Fill_Target)
ABS(Fill_Deviation,Fill_Error)
GRT(Fill_Deviation,25)OTE(Fill_Out_Of_Spec)

The first pair counts a batch down to zero. The second pair is the deviation pattern: subtract to get a signed error, take the magnitude, then compare. Set Fill_Target to 500 and try Fill_Actual at 460 and at 540, and see the same alarm catch both.

Run this rung in the simulator

What it is called on other controllers

PlatformEquivalent
Rockwell (Studio 5000)SUB
Siemens (TIA Portal)SUB
Mitsubishi (GX Works)The subtract instruction, written as -
CODESYS and IEC 61131-3SUB, or - in structured text

Common mistakes

  • Subtracting the wrong way round. A remaining count written as actual minus target counts downwards through zero and keeps going, and the lamp that should come on at zero never does.
  • Comparing a difference without taking its magnitude. An error of -30 passes a test for less than 5, so a deviation alarm built straight on a SUB result only ever catches deviation in one direction. Feed it through ABS first.

Practise it

Interactive exercises that use SUB. Each one checks your ladder against a real scan.

Related instructions

All ladder logic instructions