Back to Supported G-Codes
M98 & M99 - Subroutines
DMC File Mode: Supported
Streaming Mode: Supported
Description
M98 and M99 enable the creation and use of subroutines in G-code programs. Subroutines are reusable blocks of code that can be called multiple times, helping to reduce program size and improve maintainability for repetitive operations.
- M98: Calls a subroutine by its program number
- M99: Returns from a subroutine back to the main program
- N-labels: Define subroutine start points using N followed by a number
Syntax
; Subroutine definition
N100 ; Start subroutine 100
G1 X10 Y10 F500 ; Subroutine commands
G1 X20 Y20
M99 ; End subroutine
; Subroutine call
M98 P100 ; Call subroutine 100
M98 P100 L3 ; Call subroutine 100, repeat 3 times
Parameters
Parameter | Description | Example |
---|---|---|
P | Program number to call (1-9999) | P100 |
L | Number of times to repeat (optional, default: 1) | L5 |
Examples
Basic Subroutine
; Define a simple drilling subroutine
N200 ; Start subroutine 200
G1 Z-5 F100 ; Drill down
G4 P500 ; Dwell 0.5 seconds
G1 Z5 F500 ; Retract
M99 ; Return from subroutine
; Main program
G0 X10 Y10 ; Position for first hole
M98 P200 ; Drill hole
G0 X20 Y20 ; Position for second hole
M98 P200 ; Drill hole
Repeated Subroutine Call
; Define a step pattern subroutine
N300 ; Start subroutine 300
G1 X5 F200 ; Move 5mm in X
G1 Y1 ; Move 1mm in Y
M99 ; Return from subroutine
; Create a staircase pattern
G0 X0 Y0 ; Start position
M98 P300 L10 ; Call step pattern 10 times
Complex Machining Sequence
; Tool change and setup subroutine
N500 ; Start subroutine 500
G0 Z25 ; Retract to safe height
M5 ; Stop spindle
G4 P2000 ; Wait for spindle stop
M3 S1200 ; Start spindle at 1200 RPM
G4 P1000 ; Wait for spindle to reach speed
M99 ; Return from subroutine
; Use in main program
M98 P500 ; Setup for operation
G1 X10 Y10 Z-2 F300 ; Begin machining
Forward Declaration - Call Before Definition
; Main program calls subroutine before it's defined
G0 X0 Y0 ; Start position
M98 P1000 ; Call subroutine 1000 (defined below)
G0 X50 Y0 ; Move to next position
M98 P1000 ; Call same subroutine again
M2 ; End program
; Subroutine defined after main program
N1000 ; Start subroutine 1000
G1 Z-3 F200 ; Plunge
G1 X10 Y10 ; Cut pattern
G1 X0 Y10
G1 X0 Y0
G1 Z3 F500 ; Retract
M99 ; Return from subroutine
Note: Subroutines can be defined anywhere in the file - before or after the M98 calls that reference them. The entire file is parsed first, so all subroutines are available regardless of their position in the file.