How to Use Compare Instruction in PLC Programming
In PLC programming, the
compare instruction checks the relationship between two values, such as equal, greater than, or less than. You use it by specifying the two values and the comparison type, which then outputs a true or false result to control logic flow.Syntax
The compare instruction syntax typically involves two operands and a comparison operator. It evaluates the condition and returns a boolean result.
- Operand1: First value to compare.
- Operand2: Second value to compare.
- Operator: Type of comparison (e.g., =, >, <, >=, <=, <>).
- Result: Boolean output (true if condition met, false otherwise).
plaintext
COMPARE Operand1, Operand2, Operator
// Example: COMPARE 10, 20, <Example
This example shows how to use the compare instruction to check if a sensor value is greater than a threshold and turn on an output if true.
structured_text
VAR SensorValue : INT := 75; Threshold : INT := 50; OutputSignal : BOOL := FALSE; END_VAR // Compare if SensorValue is greater than Threshold IF SensorValue > Threshold THEN OutputSignal := TRUE; ELSE OutputSignal := FALSE; END_IF;
Output
OutputSignal = TRUE
Common Pitfalls
Common mistakes when using compare instructions include:
- Mixing data types (e.g., comparing integer with string) which causes errors.
- Using incorrect operators that do not match the intended logic.
- Not handling the false case, leading to unexpected outputs.
Always ensure operands are compatible and operators are correctly chosen.
structured_text
VAR Value1 : INT := 10; Value2 : STRING := '10'; Result : BOOL; END_VAR // Wrong: comparing INT with STRING // Result := (Value1 = Value2); // This will cause a type error // Correct: VAR Value3 : INT := 10; Value4 : INT := 10; END_VAR Result := (Value3 = Value4);
Quick Reference
| Operator | Meaning | Example |
|---|---|---|
| = | Equal to | COMPARE 5, 5, = (true) |
| > | Greater than | COMPARE 10, 5, > (true) |
| < | Less than | COMPARE 3, 7, < (true) |
| >= | Greater than or equal | COMPARE 5, 5, >= (true) |
| <= | Less than or equal | COMPARE 4, 6, <= (true) |
| <> | Not equal | COMPARE 5, 3, <> (true) |
Key Takeaways
Use the compare instruction to evaluate conditions between two values in PLC logic.
Ensure operands are of compatible data types to avoid errors.
Choose the correct comparison operator to match your control logic needs.
Always handle both true and false outcomes for reliable automation.
Refer to the quick reference table for common comparison operators and their meanings.