Skip to content
✦ Made with Docsie · generated from video

How to Write G Code for a CNC Machine

This guide shows you how to write G-code for a CNC machine to build a tool counting macro that tracks tool life, faults out automatically when a tool reaches its limit, and prompts the operator with a clear message. A macro is an automated input sequence that imitates keystrokes or mouse actions, and macro variables can significantly increase efficiency in CNC machining. Mastering macros can elevate your programming skills, since they can automate tasks such as tool counting, tool life management, and resetting messages, allowing an operator to press start and let the macro handle the rest. Because each CNC machine handles tool counters and menus differently, a custom macro is often the most reliable solution.

Manufacturing 36 steps 29 screenshots 2484 words Source video 12:03 Generated cost $4.55

Video: Secret Art of MACRO PROGRAMMING on a CNC Machine | G-Code Genius by TITANS of CNC MACHINING (2023). All credit for the demonstration goes to the creator; watch the original on YouTube. The written guide below was generated from this video by Docsie. Creator? Request a change or removal.

This guide shows you how to write G-code for a CNC machine to build a tool counting macro that tracks tool life, faults out automatically when a tool reaches its limit, and prompts the operator with a clear message. A macro is an automated input sequence that imitates keystrokes or mouse actions, and macro variables can significantly increase efficiency in CNC machining. Mastering macros can elevate your programming skills, since they can automate tasks such as tool counting, tool life management, and resetting messages, allowing an operator to press start and let the macro handle the rest. Because each CNC machine handles tool counters and menus differently, a custom macro is often the most reliable solution.

Book cover of "FANUC CNC Custom Macros" by Peter Smid displayed on a table
Book cover of "FANUC CNC Custom Macros" by Peter Smid displayed on a table

Purpose

This document explains how to write, test, and apply a G-code macro that counts tool cycles, checks tool life against a maximum value, and stops the program safely with an operator message when the tool needs to be changed.

Scope

This procedure covers writing macro variables into an existing CNC program, adding conditional (IF) logic, using GOTO statements to control program flow, displaying operator messages, resetting the tool counter, and performing the physical insert change once the macro fault triggers.

Person in "TITANS OF CNC" shirt speaking to the camera, standing next to a CNC machine control panel.
Person in "TITANS OF CNC" shirt speaking to the camera, standing next to a CNC machine control panel.

Prerequisites and required equipment

  • Access to a CNC control panel with macro programming capability (demonstrated on a FANUC Series 31i-MODEL B Plus control).
  • An existing CNC program with a defined tool path and cutoff operation.
  • Familiarity with your machine's offset and macro variable screens.
  • A reference copy of FANUC CNC Custom Macros by Peter Smid is recommended, as it covers programming resources for custom macro users at both beginner and advanced levels.

  • Safety glasses (required before handling tool holders or inserts).

  • A replacement insert and the appropriate tool for removing and installing it.
1

Confirm your macro variables are available

Before writing any code, confirm that the macro variables you plan to use are not already reserved by the machine or its subprograms. Different manufacturers reserve certain macro variables for specific functions, such as tailstock position, so checking first prevents conflicts.

  1. Press OFFSET on the control panel.
  2. Use the arrow keys to navigate to the MACRO section.
  3. Press MACRO to open the macro variable screen.
  4. Enter the variable number you intend to use and confirm it is not currently assigned.
Close-up of the CNC control panel screen showing macro variable data with the CUSTOM MACRO and EXEC MACRO buttons
Close-up of the CNC control panel screen showing macro variable data with the CUSTOM MACRO and EXEC MACRO buttons
2

Identify an unused variable for the tool counter

In this example, variable #600 is selected as the tool counter. Review the macro variable table on your control to confirm the variable shows as available before assigning it.

CNC program editor showing the line "#600=#600+1 ;" added at the end of the tool path section
CNC program editor showing the line "#600=#600+1 ;" added at the end of the tool path section
3

Review variables already in use

Some macro variables may already be populated by other macros, such as a thread macro. Review the table to see which variables hold data and which are empty so you avoid overwriting important values.

CNC program editor screen showing the line "#601=10 ;" placed at the top of the program below the program number and comments
CNC program editor screen showing the line "#601=10 ;" placed at the top of the program below the program number and comments
4

Confirm variable assignments before proceeding

Look closely at which variables are currently holding data versus which are set to zero or empty. This check prevents you from accidentally assigning a variable that another macro already relies on.

You will use two macro variables for this procedure: #600 for the tool counter and #601 for the maximum tool life. Placing the maximum tool life variable at the top of the program keeps it easy to find and adjust later.

5

Set the maximum tool life

At the top of your CNC program, add the following line to define the maximum tool life:

#601=10 ;

This sets the maximum tool life to 10 cycles, meaning the tool can produce 10 parts before the macro triggers a fault.

The value 10 represents the maximum number of cycles, or parts, the tool can produce before the macro fault activates.

Wide view of a modern CNC shop floor with multiple machines, red tool racks, overhead cranes, dust collection units, and organized workstations.
Wide view of a modern CNC shop floor with multiple machines, red tool racks, overhead cranes, dust collection units, and organized workstations.
6

Locate the tool path in your program

Scroll to the end of the tool path section in your CNC program. This is where you will insert the line that increments the tool counter after each cycle.

Wide view of a modern CNC machine shop with many machines and workstations, "TORNOS" sign visible.
Wide view of a modern CNC machine shop with many machines and workstations, "TORNOS" sign visible.
7

Add the tool counter increment

At the end of the tool path, insert the following line:

#600=#600+1 ;

This line increases the value of #600 by 1 each time the tool completes a cycle.

With both the maximum tool life variable and the counter increment in place, your program is ready for the logic that compares the two and triggers a fault when the limit is reached.

8

Choose a safe location for the fault check

Insert the fault logic immediately after the cutoff operation, not before. Faulting out before cutoff would leave a half-finished part in the spindle, creating a safety hazard and operational disruption.

9

Add the IF statement for tool life

Use an IF statement to check whether the tool counter has reached or exceeded the maximum tool life:

IF[#600 GE #601] GOTO 1234 ;

This means: if the value of #600 (tool counter) is greater than or equal to #601 (maximum tool life), jump to sequence number N1234.

CNC program editor showing the IF statement "IF[#600 GE #601] GOTO 1234 ;" highlighted at the end of the cutoff section

10

Review supported macro conditional statements

Macro programming supports several conditional and logical statements: IF [ ], WHILE [ ], AND [ ], and THEN [ ]. For this tool life logic, you only need the IF statement.

Screen listing the macro programming statements: IF [ ], WHILE [ ], AND [ ], THEN [ ]

11

Understand the IF statement structure

Think of the IF statement in simple terms: IF [condition] GOTO [action]. In your program, the condition is tool life rather than any everyday example — the logic works the same way regardless of what is being checked.

12

Break down the IF statement syntax

In the line IF[#600 GE #601] GOTO 1234 ;, #600 is your tool counter, GE stands for "greater than or equal to," and #601 is your maximum tool life. If the condition is true, the program jumps to sequence number N1234.

Close-up of the CNC screen with the line "IF[#600 GE #601] GOTO 1234;" highlighted and a finger pointing at it

Interior of a CNC machine showing the tool turret, coolant lines, and a mounted camera, illustrating where the cutoff and tool change occur
Interior of a CNC machine showing the tool turret, coolant lines, and a mounted camera, illustrating where the cutoff and tool change occur
13

Learn the comparison operators

Macro programming supports these comparison operators for building conditions:

  • GE — greater than or equal to
  • EQ — equal to
  • GT — greater than
  • LT — less than
  • LE — less than or equal to
14

Understand the GOTO statement

The GOTO command jumps to any sequence number (N number) in your program. For example, GOTO 1234 jumps to the line labeled N1234, allowing you to direct program flow based on a condition.

Screen explaining that GOTO will jump to any sequence number, labeled with an N prefix
Screen explaining that GOTO will jump to any sequence number, labeled with an N prefix
15

Search for the target sequence number

Use the control's search function to locate N1234 in your program. Enter N1234 on the keyboard and use the arrow keys to navigate to that sequence, where you will add logic to reset the counter, turn off coolant, and position the machine for the tool change.

Screen listing the comparison operators GE, EQ, GT, LT, and LE with their meanings
Screen listing the comparison operators GE, EQ, GT, LT, and LE with their meanings
CNC operator searching for sequence number N1234 on a FANUC Series 31i-MODEL B Plus control panel, with the search bar showing ^N1234. and the IF statement highlighted
CNC operator searching for sequence number N1234 on a FANUC Series 31i-MODEL B Plus control panel, with the search bar showing ^N1234. and the IF statement highlighted
16

Reset the tool counter

At sequence N1234, add the line:

#600=0 (RESET TOOL COUNTER);

This resets the tool counter to zero as the first step in the tool change sequence.

The steps that follow may vary depending on your machine type, such as a turret lathe versus a gang tool lathe. Always refer to your machine's manual for machine-specific instructions.

CNC control panel showing the program editor with the line #600=0 (RESET TOOL COUNTER); highlighted
CNC control panel showing the program editor with the line #600=0 (RESET TOOL COUNTER); highlighted
17

Move the axis to a safe position

Add the line G28 U0; to move the axis to a reference (safe) position, ensuring the tool is clear of the workpiece and safely positioned for the tool change or maintenance.

18

Turn off the coolant

Add the line M9; to turn off the coolant. This prevents coolant from running while an insert is changed or maintenance is performed.

19

Slow and stop the spindle

Add the following lines in sequence:

M103 S100 P1;
G4 U1.;
M105 P1;

The first line slows the spindle to 100 RPM, the second dwells for 1 second, and the third stops the spindle completely. The display shows a message confirming the spindle has stopped.

Close-up of the CNC screen showing the spindle stop command and confirmation message
Close-up of the CNC screen showing the spindle stop command and confirmation message
20

Display an operator message and pause the program

Add the line:

#3006=1 (CHANGE T112 CNMG TURN);

Any text placed in parentheses after #3006=1 appears as a message to the operator — in this case, "CHANGE T112 CNMG TURN." Keep messages clear and operationally relevant, since this text is intended to guide the operator's next action.

Safety note: Once this message displays, the machine faults out and prevents further operation until the message is acknowledged and the required action, such as a tool change, is completed. You cannot press start until the issue is resolved and the message is cleared.

CNC screen showing #3006=1 (CHANGE T112 CNMG TURN); with the message displayed
CNC screen showing #3006=1 (CHANGE T112 CNMG TURN); with the message displayed
21

Consider M00 as an alternative to a custom message

If your operators are well-trained and know what to look for, you can place an operator note on the M00 (program stop) line instead of a custom message. This method relies on operator awareness rather than an automated message, so use it only where your team is experienced with the program's structure.

CNC screen showing program lines including #600=0 (RESET TOOL COUNTER);, G28 U0;, M9;, M103 S100 P1;, G4 U1.;, M105 P1;, #3006=1 (CHANGE T112 CNMG TURN);, and M00; with the M00 line highlighted
CNC screen showing program lines including #600=0 (RESET TOOL COUNTER);, G28 U0;, M9;, M103 S100 P1;, G4 U1.;, M105 P1;, #3006=1 (CHANGE T112 CNMG TURN);, and M00; with the M00 line highlighted
22

Use GOTO to resume the program after the stop

After stopping the spindle and completing the required action, use a GOTO statement to continue the program from a specific line, for example:

GOTO 5678;

Use numeric labels, such as 5678, without the N prefix in the GOTO statement itself.

CNC screen showing the highlighted M112; and GOTO 5678; lines demonstrating program flow after the stop
CNC screen showing the highlighted M112; and GOTO 5678; lines demonstrating program flow after the stop
23

Navigate to the target line number

To jump to a specific line, enter the line number, such as N5678, using the keypad, and press the appropriate navigation key to move directly to that line.

24

Resume the program after the tool change

Once the tool change or maintenance is complete, press the start button to resume execution. The program restages everything as needed and continues automatically from the specified line.

Note: Tool counting menus can vary significantly between different CNC machines and can be confusing to learn due to differences in interface and terminology. Using programmatic messages and stops, as described above, standardizes the tool change process across different machines and reduces the learning curve for operators.

25

Review the complete macro logic

The full macro structure follows this pattern:

#601 = 10 (T112 CNMG MAX TOOL LIFE)
"Machining here"
#600 = #600 + 1
"CUTOFF"
IF[#600 GE #601] GOTO 1234
END OF Program (M30)
N1234 Message for Operator

These lines work together to automate tool life tracking and operator notification.

After each machining operation, the tool counter variable increments by one, ensuring accurate tracking of tool usage.

After machining and incrementing, the program executes the cutoff operation, then checks whether the tool counter has reached or exceeded the maximum tool life using IF[#600 GE #601] GOTO 1234. If the condition is met, the program jumps to line 1234, where the operator message is located.

The program repeats the machining and increment steps until the tool counter reaches the set limit (10 in this example). Once the condition is met, the program jumps past M30 (end of program) to display the operator message, instructing them to change the insert and restage the machine, minimizing downtime.

Operator pointing at the CNC program editor to show the tool path section where the counter will be added
Operator pointing at the CNC program editor to show the tool path section where the counter will be added
Whiteboard diagram outlining the CNC program logic for tool life management, including variable initialization, the increment line, cutoff, and the conditional jump
Whiteboard diagram outlining the CNC program logic for tool life management, including variable initialization, the increment line, cutoff, and the conditional jump
Whiteboard diagram illustrating the loop and the operator notification logic once the tool life limit is reached
Whiteboard diagram illustrating the loop and the operator notification logic once the tool life limit is reached
26

Run a test part to confirm the logic

Run additional parts to confirm the macro logic in a real-world scenario before relying on it in production.

27

Complete the final cycle and return to home position

Once the final part completes, the CNC machine returns to its home or rest position. The setup includes tool holders, coolant lines, and a monitoring camera. The machine is now ready to check the tool counter and display the operator message if needed.

CNC machine at rest after completing the last part, with tool holders and a monitoring camera visible
CNC machine at rest after completing the last part, with tool holders and a monitoring camera visible
28

Confirm the operator message appears

The CNC control panel displays the message "CHANGE T112 CNMG TURN," confirming the tool change condition has been met. The screen also shows part count, run time, and other relevant data.

29

Prepare to perform the tool change

Approach the CNC machine to perform the required tool change. The tool turret, spindle, and surrounding machine components are visible as you prepare to replace the worn insert, following the message prompt.

30

Remove the current insert

PPE required: Wear safety glasses before handling the tool holder or insert.

Use the appropriate tool to loosen and remove the current insert from the tool holder inside the CNC machine. Hold the replacement insert ready for installation.

Person wearing safety glasses using a tool to remove an insert from a CNC tool holder, with multiple tool holders and machine components visible
Person wearing safety glasses using a tool to remove an insert from a CNC tool holder, with multiple tool holders and machine components visible
31

Install the new insert

Place the new insert into the tool holder and secure it by tightening it with the appropriate tool.

Confirm the insert is properly seated and secured before continuing, so the machine is ready for the next operation.

32

Verify the machine after the insert change

Return to the CNC control panel and check the machine interface to confirm it is ready for operation after the insert change.

Verification and summary

Confirm the following before returning the machine to production:

  • The macro variables #600 (tool counter) and #601 (maximum tool life) are defined at the top of the program.
  • The tool counter increment line #600=#600+1 ; sits at the end of the tool path.
  • The IF statement IF[#600 GE #601] GOTO 1234 ; is placed immediately after the cutoff operation.
  • Sequence N1234 resets the counter, turns off coolant, stops the spindle, and displays the operator message.
  • A GOTO statement resumes the program after the tool change is completed and start is pressed.
  • The new insert is installed, seated, and secured, and the control panel confirms the machine is ready.
CNC control screen showing the CUSTOM MACRO table with "DATA EMPTY" highlighted to indicate available variables
CNC control screen showing the CUSTOM MACRO table with "DATA EMPTY" highlighted to indicate available variables

Key program lines for reference:

  • #601=10 ; — sets the maximum tool life.
  • #600=#600+1 ; — increments the tool counter after each cycle.
  • IF[#600 GE #601] GOTO 1234 ; — checks tool life and triggers the jump.
  • #600=0 (RESET TOOL COUNTER); — resets the counter.
  • G28 U0;, M9;, M103 S100 P1;, G4 U1.;, M105 P1; — move to safe position, stop coolant, and stop the spindle.
  • #3006=1 (CHANGE T112 CNMG TURN); — displays the operator message and pauses the program.
  • GOTO 5678; — resumes the program at the specified line after the tool change.

Always follow your specific machine's safety and operational guidelines, since the steps above are a general example that may require adaptation for your equipment.

What's next

Once you are comfortable writing a tool counting macro, you can explore additional macro programming resources, including trigonometric functions such as tangent, sine, and cosine, to expand what your macros can calculate and control.

As you gain experience, consider which additional macros — such as tool life tracking variations, custom operator messages, or other conditional logic — would be most useful for your own CNC programs.

Instructor at a desk, introducing Lesson 1: Tool Counting Macro, with relevant books visible
Instructor at a desk, introducing Lesson 1: Tool Counting Macro, with relevant books visible
Operator at CNC control panel explaining the process, pointing at the screen
Operator at CNC control panel explaining the process, pointing at the screen
Operator discussing challenges of tool counting menus on different CNC machines
Operator discussing challenges of tool counting menus on different CNC machines
Operator explaining the benefits of programmatic messages for tool changes at CNC control panel
Operator explaining the benefits of programmatic messages for tool changes at CNC control panel
Instructor gesturing towards CNC machine, preparing for practical demonstration
Instructor gesturing towards CNC machine, preparing for practical demonstration
Person holding a tool towards the camera, another person holding an exercise ball overhead, large text "CNCEXPERT.COM" displayed.
Person holding a tool towards the camera, another person holding an exercise ball overhead, large text "CNCEXPERT.COM" displayed.
Preview clips: airplane wing, colorful display, person in winter coat in a European city, presenter in CNC shop, with "NEXT TIME" and "SUBSCRIBE" prompts.
Preview clips: airplane wing, colorful display, person in winter coat in a European city, presenter in CNC shop, with "NEXT TIME" and "SUBSCRIBE" prompts.
Generation details: cost, quality tiers

Docsie billed 6,500 credits ($4.55) to analyze this 13-minute video at standard quality. The rewrite, template fill and Word/PDF exports were included. The same video at each quality tier:

QualityFrames sampledCreditsApprox. cost
Draftevery 16-30 s3,250$2.27
Standard (this guide)every 8-15 s6,500$4.55
Detailedevery 4-7 s13,000$9.10
Ultraevery 1-3 s26,000$18.20

Credits priced at $0.70 per 1,000; plans include a monthly allowance. Enterprise customers on on-premise or bring-your-own-model deployments run this on their own inference and pay no per-video credits.

Generated by Docsie Video-to-Docs on 2026-09-14 from a 12-minute video. Screenshots are frames from the source video and belong to their creator, TITANS of CNC MACHINING, whose original is embedded above. If you own this video and want the guide removed or credited differently, contact us and we will act within one business day.

Turn your own training videos into guidesJoin teams that save hours, reduce documentation work and scale training with Docsie.
See Docsie in action. No commitment.

Ready to Transform Your Documentation?

Start creating professional documentation that your users will love