CNC Subprograms and M98/M99 Explained with Practical Examples
CNC subprograms are reusable code blocks that allow you to simplify, modularize, and repeat machining operations with precision and efficiency. Using M98 to call and M99 to return, subprograms make your G-code cleaner, smarter, and more maintainable.
🧠 What Are Subprograms?
A subprogram is a separate block of G-code, stored either in the same file or as an external .nc or .O#### file, which performs a task like:
- Drilling a pattern
- Making a pocket
- Milling a contour
You can call it from your main program using M98.
🔁 Subprogram Syntax
🔹 Call a Subprogram:
M98 P1234
P1234→ Program numberO1234- Control jumps to subprogram
O1234
🔸 Loop the Call:
M98 P1234 L5
- Loops the subprogram 5 times
🔹 Subprogram Format:
O1234
G81 Z-10 R2 F100
G80
M99
O1234→ Program startM99→ Return to main program or loop
🔄 Example: Drilling a 3-Hole Pattern with a Subprogram
🔸 Main Program (O0001):
O0001
G90 G17 G21
G0 X0 Y0
M98 P2000 L3
M30
🔹 Subprogram (O2000):
O2000
G81 Z-10 R2 F100
X10
X20
G80
M99
This drills 3 holes every time O2000 is called.
📦 External Subprogram Files
Subprograms can be stored in separate files:
- Main program:
main.nc - Subprogram:
O2000.nc
Just make sure the subprogram is saved on the CNC controller or USB with a valid program number.
🧭 Subprogram Naming Rules
| Rule | Example |
|---|---|
Start with letter O | O1234 |
| Numbers only (4–5 digits) | Valid: O123, Invalid: OABC |
| No spaces or punctuation | ✅ |
Must end with M99 | ✔️ Return to main program |
📊 Benefits of Subprograms
| Advantage | Description |
|---|---|
| Code Reusability | Write once, use many times |
| Reduced Errors | Edit one place, changes everywhere |
| Easy Repetition | Use L count to repeat operations |
| Modular Logic | Organize code for better readability |
| Shorter Programs | Avoid massive blocks of repeated code |
🧪 Advanced: Nested Subprograms
You can call a subprogram from within a subprogram:
O1000
M98 P2000
M99
O2000
M98 P3000
M99
O3000
G81 Z-10 R1 F100
G80
M99
Be cautious to avoid infinite loops.
⚠️ Common Mistakes
| Mistake | Result |
|---|---|
Missing M99 in subprogram | Machine may hang or crash |
| Using wrong program number | Error: Subprogram not found |
Forgetting L count | Executes only once or not at all |
| Calling a subprogram in itself | Infinite loop — machine freeze |
🛠️ Practical Use Cases
- Bolt hole patterns
- Custom facing cycles
- Engraving repeated logos
- Probe routines
- Looped drilling or tapping cycles
✅ Summary
Subprograms using M98 and M99 are essential tools for:
- Making code modular and maintainable
- Reducing redundancy and file size
- Automating repeated operations
- Enabling nested logic and structures
Start small with subprograms — soon you’ll be building powerful, scalable CNC codebases with ease.
Leave a comment