0
0
FreertosHow-ToBeginner · 3 min read

How to Use Math Instructions in PLC Programming

In PLC programming, use math instructions such as ADD, SUB, MUL, and DIV to perform arithmetic operations on variables or constants. These instructions take input values, perform the calculation, and store the result in a specified destination register or memory location.
📐

Syntax

Math instructions in PLCs typically follow this pattern:

  • Instruction: The operation to perform (e.g., ADD, SUB, MUL, DIV).
  • Source 1: The first input value (can be a variable or constant).
  • Source 2: The second input value.
  • Destination: Where the result is stored (a variable or memory address).

Example syntax:

ADD Source1, Source2, Destination
plaintext
ADD Source1, Source2, Destination
💻

Example

This example adds two numbers stored in registers and saves the result in another register.

plaintext
ADD 10, 20, D100
SUB D100, 5, D101
MUL D101, 2, D102
DIV D102, 4, D103
Output
D100 = 30 D101 = 25 D102 = 50 D103 = 12
⚠️

Common Pitfalls

Common mistakes when using math instructions in PLCs include:

  • Using uninitialized variables as inputs, which can cause incorrect results.
  • Dividing by zero, which may cause errors or unexpected behavior.
  • Not considering data type limits, leading to overflow or truncation.
  • Forgetting to store the result in a destination register.
plaintext
DIV 10, 0, D100  ; Wrong: division by zero
DIV 10, 2, D100  ; Correct: valid division
📊

Quick Reference

InstructionDescriptionExample
ADDAdds two valuesADD 5, 3, D100 ; D100 = 8
SUBSubtracts second value from firstSUB D100, 2, D101 ; D101 = D100 - 2
MULMultiplies two valuesMUL 4, 5, D102 ; D102 = 20
DIVDivides first value by secondDIV D102, 4, D103 ; D103 = 5

Key Takeaways

Use math instructions like ADD, SUB, MUL, and DIV to perform arithmetic in PLCs.
Always specify source operands and a destination to store the result.
Avoid division by zero and uninitialized variables to prevent errors.
Check data types and ranges to avoid overflow or truncation.
Test math operations step-by-step to ensure correct logic.