PLC Programming SAPLC ProgrammingSOUTH AFRICA
Menu

reference · South Africa

IEC Math Instructions: ADD, SUB, MUL and DIV

IEC math instructions for PLC learners: check ADD, SUB, MUL and DIV with rate calculations, intermediate ranges, valid inputs and vendor-specific guidance.

Conceptual IEC math instructions study workstation with a generic controller and guarded training conveyor
Conceptual learning illustration; not vendor software, a customer installation or a measured result.

IEC math instructions let a PLC add, subtract, multiply and divide numeric values. Using ADD, SUB, MUL or DIV correctly also requires knowing the operands' types, units, permitted ranges and validity. A calculation can produce a plausible number while answering the wrong question, especially when an intermediate operation loses a fraction or exceeds its available range.

This reference gives South African PLC learners a practical arithmetic review method. The worked production-rate and setpoint examples are fictional mathematical exercises. They are not commissioning settings, native controller test results or promises that the same source code runs unchanged in every engineering package.

This site has a commercial connection to PLC Simulator. Its educational tools are an optional practice route; vendor software, licensing and target-specific verification remain separate. The illustrations show conceptual learning scenes, not customer installations or vendor interfaces.

Start with the arithmetic contract

Before selecting an instruction, write one sentence explaining the result. “Accepted pieces per minute over a completed measurement interval” is more useful than “divide count by time”. It identifies the numerator, denominator, unit and observation window. Add the valid input range, the required precision and what a consumer should see when the calculation is unavailable.

A tag name alone is insufficient. Elapsed might mean milliseconds, seconds, minutes or a controller time value. Count might be a lifetime total or the change during one window. Combining a lifetime count with the latest window duration gives a number, but it does not measure that window's production rate.

OperationMathematical roleReview question
ADDCombine quantitiesDo the quantities use compatible units and the same reporting scope?
SUBFind a differenceCan the difference be negative, and what happens across a counter reset?
MULApply a factor or form a productCan the intermediate product be represented?
DIVForm a quotientIs the divisor valid, nonzero and meaningful for this application?

For subtraction, signedness is part of the contract. A difference between two nonnegative readings may still be negative. For addition, the total of two individually valid values may exceed the result range. For multiplication and division, dimensional analysis should happen before implementation: pieces multiplied by seconds is not a production rate.

Keep a small worksheet beside the program showing each input's unit, range, type and source. Add an expected example calculated independently. That worksheet is useful when another learner reviews the routine and when a project later changes from one controller family to another.

Read operators, instruction blocks and types separately

In Structured Text, arithmetic commonly appears through operators such as +, -, * and /. Graphical languages present arithmetic through instruction blocks. Similar names do not prove identical operand conversion, overflow handling or execution behaviour across languages and targets.

A destination with a wide range does not, by itself, document the type used for every intermediate expression. Inspect the engineering system's expression rules, constant types and conversion rules. If the design needs a wider intermediate, make that choice explicit using the supported typed operands or conversions, then verify the compiled expression on the intended target.

For a mathematical example, (A + B) / C first forms a sum. A + (B / C) adds a quotient to A. With A equal to 6, B equal to 4 and C equal to 2, the answers are 5 and 8 respectively. Parentheses communicate the intended grouping and make a peer review easier; they do not make an unsuitable operand type suitable.

Distinguish numeric representation from the displayed format. A screen showing two decimal places may hide additional stored precision. Conversely, printing decimal places after an integer calculation cannot restore a fraction that was already discarded. Use the PLC data conversion and rounding reference when deciding where conversion and rounding belong in the calculation.

Do not infer that a successful compile validates engineering units, measurement quality or denominator age. Those are application requirements. A compiler can accept a calculation whose inputs belong to different time windows or whose displayed result is obsolete.

Conceptual sensor, controller and conveyor showing the stages of an industrial control process
Conceptual learning illustration; not vendor software, a customer installation or a measured result.

Worked example: thirteen pieces in forty-five seconds

Define a fictional reporting interval with 13 accepted pieces and 45 elapsed seconds. Both values describe the same completed interval. The required result is pieces per minute, so the mathematical relationship is count multiplied by 60 seconds per minute, divided by elapsed seconds.

The numerator is 780. Dividing by 45 gives the exact fraction 52/3, or approximately 17.3333 pieces per minute. A display policy of two decimal places presents 17.33. That display value is a presentation decision; calculations that need more precision should not automatically reuse the rounded display text.

StepValueMeaning
Accepted pieces13Count within this reporting interval
Elapsed seconds45Duration of that same interval
Count multiplied by 60780Numerator for the per-minute calculation
Exact rate52/3Pieces per minute
Two-decimal display17.33Rounded presentation of the rate

There are two different integer mistakes to investigate. If an implementation truncates the final positive quotient, it produces 17 instead of preserving the fraction. If it first converts 45 seconds to whole minutes by truncating 45/60, it produces a denominator of zero. Widening only the final destination cannot repair that earlier loss.

The worked model deliberately defines truncation for those negative examples; it does not assert that every vendor instruction rounds or truncates identically. Check the selected instruction with the actual source and destination types. A floating-point input mixed with an integer destination can follow different rules from an entirely integer operation.

Test additional intervals that make unit errors visible. Thirteen pieces in 60 seconds gives 13 pieces per minute; the same count in 120 seconds gives 6.5. Zero pieces in a valid 45-second window gives a valid rate of zero. None of these cases needs an arbitrary rule that the elapsed time must first reach one whole minute.

A very short positive interval can still be unsuitable for the reporting objective. The minimum observation window should come from measurement resolution and the intended statistic. It is a separate application decision, not a universal DIV requirement. Record that decision explicitly instead of burying it inside an unexplained constant.

Invalid inputs need a visible result status

For this exercise, a calculation is available only when both inputs have good quality, the count is a finite nonnegative whole number, and elapsed seconds is finite and positive. These conditions define the model. A real implementation must also enforce its chosen maximum ranges and handle how the timing and counting sources are acquired.

When an input fails validation, mark the result unavailable and record the reason. A display may retain a previous valid number for context, but it must identify that number as historical. Leaving the last rate untouched while continuing to mark it current gives downstream readers a misleading result.

Input conditionModel outcomeWhy
Count 0, elapsed 45 seconds, good qualityAvailable, rate 0A measured zero is meaningful
Count 13, elapsed 0 secondsUnavailableNo valid duration for the quotient
Count 13, negative elapsed timeUnavailableOutside this duration contract
Negative or fractional piece countUnavailableOutside this accepted-piece contract
Nonfinite value or bad input qualityUnavailableThe model cannot establish a valid measurement

Do the guard before executing the division. Avoid relying on a language's evaluation order for a compound Boolean expression that also contains the divide unless that behaviour is documented. A clearly separated validation branch and calculation branch are easier to inspect and test.

Do not silently replace an invalid duration with one second just to obtain a number. That changes the meaning of the measurement. If a fallback estimate is genuinely required, give it its own status and documented method. A consumer should be able to distinguish a measured rate, a historical value and an estimate.

Think about when the inputs become available together. A routine that reads a new count with an old duration may create a transient error despite both tags being individually valid. Capture a coherent reporting record or use an agreed update protocol. The PLC scan-cycle guide explains why program order and data updates belong in this review.

Illustrated study desk with a laptop, notebook and controller for planning a PLC learning route
Conceptual learning illustration; not vendor software, a customer installation or a measured result.

Worked example: a small final value with a large intermediate

Consider a second fictional contract: map an integer percentage from 0 through 100 to a teaching scale from 0 through 1000. This scale is deliberately independent of any analogue module. The mathematical calculation is percentage multiplied by 1000, then divided by 100.

At 75 percent, the intermediate product is 75,000 and the final result is 750. A signed 16-bit storage range ends at 32,767, so that intermediate cannot fit in such a range even though the final result can. This is a range comparison, not a claim that every compiler performs the multiplication in 16 bits or silently wraps it.

At the upper accepted input of 100, the product reaches 100,000. A signed 32-bit intermediate can represent that range. The implementation must actually perform the operation with the intended types; declaring a final destination as DINT is not a substitute for checking the evaluation rules.

For this particular scale, the relationship simplifies exactly to percentage multiplied by 10. That removes the division and reduces the largest mathematical intermediate to 1000. The simplification is valid because the factors are fixed and the contract is known. It is not a general instruction to reorder arbitrary floating-point or integer expressions without checking their effects.

Integer percentageProduct before divisionFinal teaching-scale value
000
1100010
3333,000330
7575,000750
100100,0001000

Reject percentages below zero or above 100 in this model. Also reject fractional inputs because this version explicitly accepts whole percentages. If tenths of a percent are required later, revise the input representation, scaling factors and tests together. Do not quietly truncate an operator's requested value and present it as faithfully accepted.

A real analogue output needs the exact module's representation, configured range and diagnostic behaviour. A number copied from another module's example is not a universal full-scale value. Continue with the analogue scaling and resolution guide for the distinction between raw counts, engineering units and usable resolution.

What the vendor documentation actually supports

Siemens TIA Portal DIV and ENO

Siemens' STEP 7 V21 FBD documentation describes DIV as IN1 divided by IN2 and lists conditions affecting ENO. It also explicitly describes a zero-divisor case in which ENO is true and the output depends on the selected type. Consequently, an ENO check alone should not be treated as proof that the application's denominator was valid. Check the divisor and application conditions before division, and verify the exact CPU, language and operand configuration. See the Siemens V21 DIV reference.

Allen-Bradley Studio 5000 DIV

Rockwell's Studio 5000 version 38 reference states that DIV truncates when its sources and destination are integers. It lists division by zero as minor fault type 4, code 4, and documents different zero-divisor results for integer and floating-point divisions. Its math-status table also distinguishes controller generations. This does not support a blanket claim that every Allen-Bradley divide leaves the previous result unchanged. The same page directs Structured Text users to the / operator rather than a named DIV instruction call. See the version 38 DIV instruction documentation.

CODESYS division monitoring

The CODESYS DIV reference explicitly says zero-division results can depend on the target. Its monitoring documentation explains that implicit checking functions can be included in an application. The illustrated CheckDivReal implementation substitutes one for a zero divisor. That can prevent the original zero division while changing the numerical meaning of the result. Inspect the project's actual monitoring implementation instead of assuming that a returned number proves valid input. See the CODESYS division-checking functions.

These references support specific behaviours, not a universal fault-recovery recipe. Record the software version, controller, instruction form and types alongside your native test results. Do not change unrelated fault settings to conceal invalid arithmetic.

Two illustrated learners discussing a controller program beside a guarded training conveyor
Conceptual learning illustration; not vendor software, a customer installation or a measured result.

Build a test sheet that can catch a wrong formula

Start with independently calculated expected values, then run the intended implementation against them. Testing only that the output changes is weak evidence. Testing a second implementation that repeats the same mistaken unit conversion can also give false confidence.

For the rate example, use exact fractions as the mathematical reference. Check 13/45 of a minute correctly through 13 multiplied by 60 divided by 45. Add zero count, longer duration, bad quality, zero duration and invalid numeric inputs. Record availability separately from the numeric result in every row.

For the teaching scale, check every whole percentage from 0 through 100 against the independently simplified relationship of percentage multiplied by 10. Inspect the intermediate at 33 percent, where 33,000 already exceeds a signed 16-bit range. The 75-percent example is useful, but it should not be the only range test.

A native test report should capture operand declarations, typed constants, result values, status information and the engineering environment. It should also cover disabled execution and re-enabling, so a retained old result cannot accidentally appear fresh. Those observations are distinct from the mathematical fixtures checked for this article.

Use PLC program-testing practice to structure expected outcomes and failure cases. Check which educational exercises are available; the product page is not a guarantee that it executes arbitrary vendor arithmetic code or reproduces a target controller's fault behaviour.

South African course and portfolio applications

For an electrician, millwright or instrumentation learner studying PLC arithmetic in South Africa, a useful portfolio item is a calculation with a traceable contract and a completed test sheet. Explain the measurement window, units, intermediate range and unavailable-result behaviour before showing the final rung or expression.

A training provider can adapt the fictional rate exercise to a packaging count, a water-treatment reporting interval or a workshop production record. The arithmetic method transfers, but the measurement source and operational requirements need their own review. Replacing a process label with a city name does not make the engineering example locally verified.

When comparing courses in Gauteng, KwaZulu-Natal or the Western Cape, ask which controller and engineering-software versions are used for assessed arithmetic exercises. Ask whether learners inspect types and error status, or merely reproduce an instructor's displayed answer. Request an example assessment with invalid inputs and an explanation of how individual practical work is marked.

For remote study, Structured Text learning exercises can help with expression reading and logic organisation. Confirm the current exercise scope and access terms. Keep vendor compilation evidence separate from educational practice, and do not describe a study worksheet as a recognised qualification or a production commissioning record.

Illustrated learner comparing controller status indicators with a guarded conveyor training model
Conceptual learning illustration; not vendor software, a customer installation or a measured result.

Questions learners ask about PLC arithmetic

Why does my PLC division lose decimal places?

Inspect the source types, intermediate operation and destination conversion. A fraction may be discarded during integer arithmetic before assignment, or rounded during a later conversion. A display format can hide precision too. Check each stage with a known fractional example rather than assuming the final tag's appearance reveals the entire calculation.

Should I multiply before dividing in PLC scaling?

Compare the precision and intermediate range for both orders. Multiplying first may preserve information that an early integer division discards, but it may require a larger intermediate. The fictional 75-percent example demonstrates both concerns. Use an exact simplification when the contract permits it, and verify the selected types.

Is a zero production rate an arithmetic error?

Not necessarily. Zero accepted pieces during a valid positive reporting interval gives a valid zero rate. Missing quality or a zero interval is different and should produce an unavailable status in this model. A screen that uses zero for both conditions prevents an operator from distinguishing no production from no valid measurement.

Can I use a small replacement number instead of zero?

Only under a deliberately specified estimation or fallback policy. Replacing the denominator changes the calculated quantity and can create an extreme result. A generic tiny constant does not establish measurement validity. Identify the failure, preserve the original input for diagnosis and communicate whether any displayed number is estimated or historical.

Does REAL solve every arithmetic problem?

No. Floating-point representation does not correct incompatible units, stale inputs, invalid denominators or a flawed reporting window. It also has finite precision. Use a representation suitable for the required range and resolution, then verify comparisons and conversion behaviour at the boundaries relevant to the application.

What should I explain in a PLC interview?

Describe the quantity first, then the input contract, formula, types and failure policy. Walk through a normal case and a deliberately invalid case. Show where a large intermediate or an early integer division could change the result. That gives the interviewer inspectable reasoning instead of an unsupported claim that the instruction always works the same way.

Illustrated PLC project portfolio with a process diagram, test notes and a laptop showing logic
Conceptual learning illustration; not vendor software, a customer installation or a measured result.

A practical arithmetic review sequence

Write the required unit and reporting window, confirm input quality, and calculate an expected answer independently. Bound every intermediate before choosing operand types. Put invalid-input handling before the arithmetic and define how consumers recognise unavailable or historical results.

Then verify the selected native instruction and record what happens at relevant boundaries. Keep the mathematical worksheet, program declarations and observed status together. A useful arithmetic reference is not just a list of ADD, SUB, MUL and DIV names: it makes the calculation's meaning and limitations visible to the next person who reads the program.

By PLC Programming SA · Last updated 2026-09-12