Mittwoch, 16. März 2022

RRF - Loops and Conditional Gcode

Description

Since version 3.01 of the Reprap Firmware, a bunch of meta commands are supported that include conditional gcode and loops. This is a rarely used feature but it can be very useful for more advanced macros or even print jobs. But what is it exactly? 
Conditional gcode is pretty much what you might guess, it allows executing parts of the code only if certain conditions are met using an "if" statement much like in any programming language. And loops can be used to execute part of the gcode over and over again until some condition is met. These structures are well known in most programming languages but is still somewhat unusual in the world of gcode.


Example

The following gcode is used to test the repeatability of a bed probe 6 times in a row and report the result and statistics of the test. In this case it would be simple enough to just run G30 command 6 times in a row, but it demonstrates how the meta codes can be used and would allow for easy parameterizing, running it N times:

G28                   ; home printer
G1 Z5 F300            ; lift nozzle to x=5mm
G1 X125 Y100 F3600    ; move toolhead to center of the bed

echo "Testing Z-Probe 6 times and reporting statistics"
while true            ; start a loop without exit clause
                      ; 'iterations' is a built in variable starting at 0
    G30 P{iterations} X125 Y100 Z-99999 F5000        
    ; lower toolhead until probe triggers, append result
    G1 Z5 F5000       ; lift nozzle back up to 5mm
  
    if iterations == 5    ; test if the variable itearation has reached the value 5
        G30 P{iterations} X125 Y100 Z-99999 F5000 S-1    
        ; lower toolhead until probe triggers, append result
        break    ; exit the loop

This example utilizes the  conditional "if" statement as well as the "loop" function and the internal variable "iterations". Please see docs.duet3d.com for more information.