How to Write G Code for CNC: Basic Guide and Examples
G-code for CNC, you create a text file with commands that control machine movements and actions using codes like G00 for rapid moves and M03 to start the spindle. Each line usually contains a command and coordinates or parameters to tell the CNC what to do step-by-step.Syntax
G-code commands are written line by line. Each line can include a G command (motion or function), coordinates (X, Y, Z), and other parameters like feed rate (F) or spindle speed (S). Lines usually start with a line number (optional) and end with a command to move or perform an action.
G00: Rapid positioningG01: Linear interpolation (cutting move)X, Y, Z: CoordinatesF: Feed rate (speed of cutting)M03: Spindle on clockwiseM05: Spindle stop
N10 G00 X0 Y0 Z0 N20 M03 S1000 N30 G01 X50 Y50 F150 N40 M05 N50 G00 X0 Y0
Example
This example shows a simple CNC program that moves the tool to the start, turns on the spindle, cuts a straight line, stops the spindle, and returns to start.
N10 G00 X0 Y0 Z5
N20 M03 S1200
N30 G01 Z-1 F100
N40 G01 X50 Y0 F200
N50 G01 X50 Y50
N60 G01 X0 Y50
N70 G01 X0 Y0
N80 M05
N90 G00 Z5Common Pitfalls
Beginners often forget to set the spindle speed or feed rate, causing tool damage or poor cuts. Another mistake is not moving the tool to a safe height before rapid moves, risking crashes. Also, missing M05 to stop the spindle can be unsafe.
Always check coordinate units (mm or inches) and machine zero points before running code.
Wrong: N10 G00 X0 Y0 Z-5 N20 M03 N30 G01 X50 Y50 Right: N10 G00 X0 Y0 Z5 N20 M03 S1000 N30 G01 Z-1 F100 N40 G01 X50 Y50 F200
Quick Reference
| Code | Meaning | Example |
|---|---|---|
| G00 | Rapid move (non-cutting) | G00 X10 Y10 |
| G01 | Linear cut move | G01 X20 Y20 F150 |
| M03 | Spindle on clockwise | M03 S1200 |
| M05 | Spindle stop | M05 |
| F | Feed rate (cutting speed) | F100 |
| S | Spindle speed (RPM) | S1000 |
| X, Y, Z | Coordinates | X50 Y50 Z-1 |