How to Use If Then in CNC Macro Programming
In CNC macro programming, use the
IF statement followed by a condition and THEN to execute commands when the condition is true. The syntax is IF [condition] THEN [commands], allowing decision-making in your CNC programs.Syntax
The IF THEN statement in CNC macro lets you run commands only if a condition is true. It checks a condition and executes the following commands if the condition holds.
- IF: starts the condition check
- condition: a logical test (e.g., #100 EQ 1 means variable 100 equals 1)
- THEN: separates the condition from the commands to run
- commands: CNC instructions or macro variables to execute if true
cnc_macro
IF [condition] THEN [commands]
Example
This example checks if variable #100 equals 1, then moves the tool to position X100 Y100. If the condition is false, it skips the move.
cnc_macro
O1000; #100=1; IF [#100 EQ 1] THEN GOTO 10; GOTO 20; N10 G01 X100 Y100 F100; N20 M30;
Output
The program moves the tool to X100 Y100 only if #100 equals 1; otherwise, it skips that move.
Common Pitfalls
Common mistakes include:
- Forgetting to enclose the condition in square brackets
[]. - Using incorrect comparison operators (use
EQ,NE,GT,LT, etc., not symbols like == or !=). - Not following
THENwith valid commands or labels. - Missing line numbers or labels when using
GOTOinsideIF THEN.
Correct usage example:
cnc_macro
IF [#100 EQ 1] THEN GOTO 10; ! Wrong: IF #100 == 1 THEN GOTO 10; ! Wrong: IF [#100 EQ 1] GOTO 10;
Quick Reference
| Element | Description | Example |
|---|---|---|
| IF | Starts the condition check | IF [#100 EQ 1] THEN ... |
| Condition | Logical test inside brackets | [#100 GT 0] |
| THEN | Separates condition from commands | THEN GOTO 10 |
| Commands | Actions if condition is true | GOTO 10, M98, variable assignments |
| Comparison Operators | Used in conditions | EQ (equal), NE (not equal), GT (greater), LT (less) |
Key Takeaways
Use IF [condition] THEN [commands] to run commands only when the condition is true.
Always enclose conditions in square brackets and use CNC macro comparison operators like EQ, NE, GT, LT.
Follow THEN with valid CNC commands or labels to avoid errors.
Use line numbers or labels with GOTO inside IF THEN for clear program flow.
Test your macro logic carefully to prevent unexpected machine moves.