How to Write G Code for CNC Milling: Basic Guide
To write
G-code for CNC milling, you create a sequence of commands that control the machine's movements and operations using codes like G00 for rapid moves and G01 for controlled cutting. Each line typically includes a command, coordinates, and feed rates to guide the milling tool precisely.Syntax
G-code commands control the CNC milling machine. Each line usually has:
- G-code command (e.g.,
G00,G01) to specify the action. - Coordinates (X, Y, Z) to move the tool to a position.
- Feed rate (F) to control speed during cutting.
- Optional codes for spindle speed (S) and tool changes (M).
Commands are written line by line and executed in order.
gcode
G00 X0 Y0 Z5 ; Rapid move to X0 Y0 Z5 M03 S1200 ; Start spindle at 1200 RPM G01 Z-1 F100 ; Move down to Z-1 at feed rate 100 G01 X50 Y0 F200 ; Cut in X direction at feed rate 200 M05 ; Stop spindle
Example
This example shows a simple milling operation that moves the tool to start, lowers it to cut, moves in a straight line, and then stops the spindle.
gcode
G21 ; Set units to millimeters G90 ; Use absolute positioning M06 T1 ; Tool change to tool 1 M03 S1500 ; Start spindle at 1500 RPM G00 X0 Y0 Z5 ; Rapid move to start position above workpiece G01 Z-2 F100 ; Lower tool into material at feed rate 100 G01 X50 Y0 F200 ; Mill straight line in X direction G01 X50 Y50 ; Mill straight line in Y direction G00 Z5 ; Retract tool to safe height M05 ; Stop spindle M30 ; End program
Common Pitfalls
Common mistakes when writing G-code for CNC milling include:
- Forgetting to set units with
G20(inches) orG21(millimeters). - Not using
G90(absolute) orG91(incremental) positioning correctly. - Omitting spindle start (
M03) or stop (M05) commands. - Failing to set feed rates (
F) causing tool damage or poor cuts. - Not retracting the tool safely before rapid moves (
G00).
Example of wrong and right usage:
gcode
; Wrong: No feed rate and no spindle start G01 X10 Y10 ; Right: Feed rate and spindle start included M03 S1200 G01 X10 Y10 F150
Quick Reference
| G-code | Meaning |
|---|---|
| G00 | Rapid positioning (fast move without cutting) |
| G01 | Linear interpolation (controlled cutting move) |
| G02 | Clockwise arc move |
| G03 | Counterclockwise arc move |
| G20 | Set units to inches |
| G21 | Set units to millimeters |
| G90 | Absolute positioning |
| G91 | Incremental positioning |
| M03 | Spindle on (clockwise) |
| M05 | Spindle stop |
| M06 | Tool change |
| F | Feed rate (speed of cutting) |
| S | Spindle speed (RPM) |
Key Takeaways
Start every G-code program by setting units and positioning mode with G20/G21 and G90/G91.
Use G00 for fast moves and G01 for cutting moves with proper feed rates.
Always start and stop the spindle with M03 and M05 commands.
Include safe tool retraction before rapid moves to avoid crashes.
Test your code on simulation software before running on the actual CNC machine.