0
0
Ev-technologyHow-ToBeginner · 3 min read

How to Use While Loop in CNC Macro Programming

In CNC macro programming, use the WHILE loop to repeat a block of code while a condition is true. The syntax starts with WHILE [condition] DO and ends with ENDWHILE. This loop helps automate repetitive tasks efficiently.
📐

Syntax

The WHILE loop in CNC macro repeats commands as long as the condition is true.

  • WHILE [condition] DO: Starts the loop and checks the condition.
  • Commands: The code to repeat.
  • ENDWHILE: Ends the loop.

The condition usually compares variables or parameters.

cnc_macro
WHILE [#100 LT 5] DO
  #100 = [#100 + 1]
  G01 X[#100 * 10] Y0
ENDWHILE
💻

Example

This example moves the tool in the X direction in steps of 10 units, repeating 5 times using a WHILE loop.

cnc_macro
O1000
#100 = 0
WHILE [#100 LT 5] DO
  #100 = [#100 + 1]
  G01 X[#100 * 10] Y0 F100
ENDWHILE
M30
Output
Moves tool to X=10, X=20, X=30, X=40, X=50 sequentially
⚠️

Common Pitfalls

Common mistakes when using WHILE loops in CNC macros include:

  • Forgetting to update the variable in the loop, causing an infinite loop.
  • Using incorrect condition syntax, which prevents the loop from running.
  • Not ending the loop with ENDWHILE, causing syntax errors.

Always ensure the loop variable changes inside the loop to avoid infinite loops.

cnc_macro
;; Wrong: Infinite loop example
#100 = 0
WHILE [#100 LT 5] DO
  G01 X[#100 * 10] Y0
ENDWHILE

;; Correct: Variable increment included
#100 = 0
WHILE [#100 LT 5] DO
  #100 = [#100 + 1]
  G01 X[#100 * 10] Y0
ENDWHILE
📊

Quick Reference

KeywordDescription
WHILE [condition] DOStart loop if condition is true
CommandsCode to repeat while condition is true
ENDWHILEEnd of the while loop
Condition examples#100 LT 5 (less than 5), #101 EQ 10 (equals 10)
Variable updateMust change inside loop to avoid infinite loop

Key Takeaways

Use WHILE [condition] DO ... ENDWHILE to repeat code while a condition holds true.
Always update the loop variable inside the loop to prevent infinite loops.
Conditions use standard comparison operators like LT (less than) and EQ (equals).
End every WHILE loop with ENDWHILE to avoid syntax errors.
Test loops carefully to ensure they run the expected number of times.