How to Write G Code for CNC Machine
This guide shows the order we actually follow when programming a part by hand. You will get the block structure, the codes that matter, and the numbers we put in F, S, and Z. Read it and you can write a short program, read one you were handed, and tell which moves are risky.

Key takeaways
What a CNC block actually contains
A G code program is a list of blocks, and one block is one line the control reads left to right. Most blocks follow the same order: N for line number, G for the motion or mode, X Y Z for coordinates, then I J K for arc centers, then F, S, and T. The order is not decoration. It is how the control parses the line, and Fanuc-style controls will fault on a block that breaks it.
Every block needs a modal memory in your head. G codes stay active until another G code in the same group replaces them. G01 stays on until you call G00 or G02. F stays on until you write a new F. That is why a program can look short and still cut a complex shape, and it is also why a missing G80 after a canned cycle ruins the next hole.
Comments go in parentheses on most controls, or after a semicolon on some. Use them. A block like (Rough OD, 12 mm end mill) costs nothing and saves the next person twenty minutes. Keep the comments in English and keep them short, because some older controls truncate long comment lines.
A single block also has a length limit on many machines. If you chain three arcs in one line with I J K on each, split them. Long blocks are where typos hide. When we review a hand-written program, we look at block length before we look at the geometry.
The G and M codes worth memorizing first
You do not need the whole code list to start. You need G00 rapid, G01 feed, G02 and G03 arcs, G17 to G19 planes, G20 and G21 units, G28 return home, G40 to G42 cutter comp, G43 tool length offset, G54 to G59 work offsets, and G80 to cancel a canned cycle. That is the core. Everything else can be looked up.
On the M side, M03 spindle forward, M05 stop, M06 tool change, M08 coolant on, M09 coolant off, M30 end and rewind. Tool changes are the common crash point. Always retract Z to a safe height and cancel comp before M06. A tool change at Z-2 mm is a broken holder, not a broken part.
Units are a silent killer. G20 is inches, G21 is millimeters. Put the right one in the first three lines. We have seen a program written in millimeters run on a machine left in inch mode; the part was cut at roughly one twenty-fifth of the intended size.
G90 absolute and G91 incremental belong near the top too. Most production programs run G90. Incremental moves are useful for repeated patterns, but they compound errors. If one incremental block is wrong, every following position is wrong by the same amount.
How to set feed rate and spindle speed
Feed rate starts with chip load, not with a number someone said in the shop. Take the recommended chip load per tooth for the material and tool diameter, multiply by the number of teeth, multiply by RPM. A 12 mm three-flute carbide end mill in 6061 aluminium at 8,000 RPM with 0.05 mm per tooth gives 1,200 mm/min. Write F1200.
Spindle speed comes from surface speed. For aluminium, 300 to 500 m/min is a normal band with carbide. For 304 stainless, drop to 80 to 120 m/min. For titanium, lower again, 40 to 60 m/min, and keep the tool moving. Rubbing is what kills titanium tools, not speed.
Depth of cut and stepover go with the feed. In aluminium you can often run axial depth equal to one tool diameter and radial stepover of 5 to 10 percent of diameter in a trochoidal path. In harder steels halve that. If the machine starts to chatter, reduce radial engagement before you reduce feed, because feed too low makes the tool rub.
Plunge moves are the exception. Never plunge at the cutting feed. Use a ramp or helix entry where the control supports it, or plunge at 30 to 50 percent of the cutting feed. Straight plunges into steel at full feed are how you break a three-flute in the first ten seconds.
Work offsets, tool length, and safe Z
G54 is the work offset you will use most. Set it from the part datum, not from the corner of the vise. Pick a datum that appears on the drawing so an inspector can measure the same point. If the drawing dimensions from the top face and a bore center, set G54 there and write every coordinate from that origin.
Tool length offset goes in the H register called by G43. G43 H01 Z50 lifts the tool to 50 mm above the work offset in the current Z. Get the sign wrong and the tool drives into the table. Always call G43 on the same block as the first Z move, and always with a positive Z.
Safe Z is a habit, not a code. We use 50 mm above the stock for tool changes and 5 mm for rapid moves between features. On a tall part, 50 mm may still clip a clamp, so check the fixture in the simulation. Retract height is set in CAM, but in hand-written code you decide it line by line.
G28 sends the machine home through an intermediate point. G28 G91 Z0 is the common form. It is safe if the path is clear, and dangerous if a vise or rotary table sits in the way. On a five-axis machine, park the rotary axes before any G28 move.
Write G Code for CNC Machine: step by step
Follow the order below. Each step lists what to write and what usually goes wrong.
- 1Start with the safe headerFirst block: G21 G17 G40 G49 G80 G90. This sets millimeters, XY plane, cancels comp, cancels tool length, cancels canned cycles, and locks absolute mode. Skipping the cancels is the most common cause of a first-move crash.
- 2Add the program number and commentO1001 (BRACKET OP1) on the first two lines. Keep the program number unique. Duplicate numbers overwrite each other in machine memory.
- 3Call the tool and spin it upT01 M06, then S8000 M03, then G43 H01 Z50. Spin up before the tool reaches the part. Never combine M06 and M03 on one block.
- 4Set the work offsetG54 in the same block as the first positioning move, for example G54 G00 X0 Y0. Confirm the offset was probed or touched off before you press cycle start.
- 5Move to the first cut pointRapid in XY at safe Z, then rapid down to 2 mm above the stock. Feed the last 2 mm at cutting feed. The move from safe Z to stock is where most plunges into a clamp happen.
- 6Cut with G01, G02, G03Use G01 with F for straight moves. For arcs use G02 clockwise and G03 counterclockwise with I J for the center relative to the start point, or R for the radius. Do not mix I J and R in the same arc.
- 7Apply cutter compensation correctlyG41 left or G42 right, then a lead-in move longer than the tool radius, then the contour. Cancel with G40 on a lead-out move. Comp on a zero-length move does nothing and alarms out on many controls.
- 8Retract, stop, and end the programG00 Z50, M09, M05, then G28 G91 Z0 or a safe park position, then M30. Leave the machine in a state the next operator can trust.
Feeds, speeds, and tolerances by material
Starting points for carbide tooling on a rigid machine. Adjust for tool stick-out and fixture stiffness.
| Material | Surface speed | Chip load, 12 mm 3-flute | Typical tolerance we hold |
|---|---|---|---|
| 6061 aluminium | 300–500 m/min | 0.05 mm/tooth | ±0.005 mm |
| 7075 aluminium | 200–350 m/min | 0.04 mm/tooth | ±0.005 mm |
| 304 stainless | 80–120 m/min | 0.03 mm/tooth | ±0.005 mm |
| 17-4PH stainless | 60–100 m/min | 0.02 mm/tooth | ±0.005 mm |
| Ti-6Al-4V | 40–60 m/min | 0.02 mm/tooth | ±0.005 mm |
| P20 tool steel | 60–90 m/min | 0.02 mm/tooth | ±0.005 mm |
| POM plastic | 300–500 m/min | 0.08 mm/tooth | ±0.02 mm |
When to write it yourself, and when to hand it over
Hand-code simple parts with a few tools and open geometry. For deep pockets, thin walls, five-axis features, or tolerances at ±0.005 mm, let a shop with the machine and the post handle the programming. That is where simulation and proven fixtures pay for themselves.
Common questions
How do I write G code for CNC machine if I only have a drawing?
Start by picking a datum that appears on the drawing, then set G54 from that point. List every feature in cutting order: face, rough, finish, drill, tap. Write one tool per section and keep the sections separate.
You do not need CAM for a simple part. Two or three tools and a dozen features are manageable by hand. Beyond that, a CAM post is faster and less error-prone than typing coordinates.
What is the difference between G code and M code?
G codes control motion and machine modes: positioning, feed, arcs, planes, offsets, compensation. M codes control on and off actions: spindle, coolant, tool change, program end.
A rough rule: if it changes the geometry of the path, it is a G code. If it switches something on or off, it is an M code.
Can the same G code run on any CNC machine?
Mostly, at the basic level. G00, G01, G02, G03, G17, G21, G54, and M03 are close to universal. Differences appear in canned cycles, tool change syntax, and high-speed look-ahead settings.
Fanuc, Siemens, Mitsubishi, and Heidenhain all have proprietary variations. Always check the machine manual before running a program written for a different control.
Why does my tool break on the first plunge?
Usually feed, not speed. A straight plunge at full cutting feed in steel or titanium overloads the center of the tool, where the surface speed is near zero. Ramp or helix into the cut instead.
Second cause is runout. Check the holder and the tool stick-out. A tool hanging 60 mm out of a standard holder will chatter and snap even at correct feed.
Do I need to learn G code to work with a machining supplier?
Not to write it, but reading it helps. When you can read a program you can tell whether a supplier is using the right tool for a deep pocket, or whether a tight tolerance is being held with a finishing pass or just claimed.
For our own work, every program is checked against the drawing and simulated before the first cut.
How do I keep a hand-written program from scrapping a part?
Simulate first, then run a dry pass with the spindle off and Z shifted up 50 mm. Watch the position display at each tool change. Then run the first part in single block with the feed override at 25 percent.
Keep a printed setup sheet with the tool list, offsets, and stock size. Most scrap comes from a setup mismatch, not from a wrong coordinate.
Send us your drawing, get a quote in 12 hours
Upload a STEP or DXF file and we return a quotation with free DFM analysis within 12 hours. No minimum order quantity, from one prototype to 10,000+ part runs.
12-hour quote100% inspection±0.005 mmNo MOQ