CNC G and M Codes Explained

CNC G and M Codes Explained: A Complete Beginner’s Guide to Programming CNC Machines

If you’re new to CNC machining, G-codes and M-codes are the two most important types of commands you’ll encounter. In simple terms: G-codes control the movement and positioning of the cutting tool, while M-codes control miscellaneous machine functions such as spindle on/off, coolant, and program stop. Understanding these codes is essential for reading, writing, or editing any CNC program.

This guide covers the most frequently used G and M codes, their syntax, common real‑world examples, and practical tips to help you start programming with confidence.

01What Are G-Codes? (Preparatory Functions)

G-codes (also called preparatory functions) tell the machine how to move the tool or workpiece. They define the type of motion, units, plane selection, and canned cycles. Most G-codes are modal, meaning they stay active until replaced by another G-code in the same group.

Most Common G-Codes (Grouped by Function)

G-CodeFunctionTypical Use
G00Rapid positioningMove tool quickly to a start point (no cutting)
G01Linear interpolationStraight‑line cutting at a programmed feed rate
G02Circular interpolation (clockwise)Cut arcs or full circles clockwise
G03Circular interpolation (counter‑clockwise)Cut arcs counter‑clockwise
G17XY plane selectionDefault plane for milling
G18XZ plane selectionFor lathe or specific milling operations
G19YZ plane selectionFor side milling or 3D work
G20Inch unitsAll coordinates in inches
G21Metric unitsAll coordinates in millimeters
G40Cutter compensation cancelTurn off tool radius offset
G41Cutter compensation leftOffset tool left of programmed path
G42Cutter compensation rightOffset tool right of programmed path
G43Tool length compensation (positive)Apply tool length offset
G49Tool length compensation cancelTurn off length offset
G54 – G59Work coordinate systemsSelect fixture offsets (G54 = first fixture)
G80Cancel canned cycleEnd drilling, tapping, or boring cycles
G81Simple drilling cycleDrill one hole with no dwell
G83Peck drilling cycleDeep hole drilling with chip breaking
G90Absolute positioningCoordinates from fixed zero point
G91Incremental positioningCoordinates relative to current tool position
G94Feed per minuteFeed rate in inches or mm per minute
G95Feed per revolutionFeed rate per spindle revolution (lathe)

Real‑World Example: Milling a Rectangular Pocket

Suppose you need to mill a 50mm x 30mm rectangular pocket, 5mm deep, starting at X20 Y20 (absolute coordinates). A typical program segment using G-codes would look like this:

G21 G90        ; Metric units, absolute positioning
G54            ; Use work offset #1
S1200 M03      ; Spindle speed 1200 RPM, start clockwise
G00 X20 Y20    ; Rapid to pocket start corner
G01 Z-5.0 F100 ; Feed down to depth at 100 mm/min
G01 X70 F150   ; Cut to X70 (50mm length)
G01 Y50        ; Cut to Y50 (30mm width)
G01 X20        ; Cut back to X20
G01 Y20        ; Return to start corner
G00 Z10        ; Rapid retract
M30            ; Program end

In this sequence, G00/G01 control the motion; G21 sets metric; G90 sets absolute; G54 selects the fixture offset. Notice that G01 (linear cut) remains active after the first use – that’s modal behavior.

02What Are M-Codes? (Miscellaneous Functions)

M‑codes turn auxiliary machine functions on or off. Unlike G‑codes, many M‑codes are non‑modal – they execute once and then stop affecting the program until another M‑code changes the state.

Most Common M-Codes

M-CodeFunctionTypical Use
M00Program stopStop execution (press cycle start to resume)
M01Optional stopStop only if operator enables “optional stop”
M02Program endEnd program (no rewind)
M03Spindle on (clockwise)Start spindle rotating clockwise
M04Spindle on (counter‑clockwise)Start spindle rotating counter‑clockwise
M05Spindle stopStop spindle rotation
M06Tool changeStop program, change tool (manual or automatic)
M07Mist coolant onTurn on mist coolant
M08Flood coolant onTurn on flood coolant
M09Coolant offTurn off all coolant
M30Program end and rewindEnd program, reset to top, rewind tape/disk
M98Subprogram callJump to a separate subprogram
M99Subprogram returnReturn from subprogram to main program

Real‑World Example: Drilling with Coolant

Imagine you need to drill four holes, then stop the spindle and coolant. A typical block might be:

N10 G21 G90 G54
N20 M08             ; Flood coolant on
N30 S800 M03        ; Spindle 800 RPM clockwise
N40 G00 X30 Y30     ; Position to first hole
N50 G81 Z-15 R2 F80 ; Drill cycle (G81) – hole depth Z-15, retract plane R2
N60 X50 Y30         ; Second hole
N70 X50 Y50         ; Third hole
N80 X30 Y50         ; Fourth hole
N90 G80             ; Cancel drill cycle
N100 G00 Z10        ; Retract
N110 M05            ; Spindle stop
N120 M09            ; Coolant off
N130 M30            ; Program end and rewind

Here M08 turns on coolant before drilling, M05 and M09 turn off spindle and coolant after the operation. This sequence matches what you would see in thousands of real machine shops every day.

03How G-Codes and M-Codes Work Together

In a typical CNC program, G‑codes and M‑codes are placed on the same line or on separate lines. The machine executes them in the order written. A few important rules:

One G‑code from each modal group can appear on the same line. For example, you can combine G21 (units) and G90 (positioning) because they belong to different groups.

Multiple M‑codes on the same line are not allowed in most controls (some newer controls accept two M‑codes). Always put M‑codes on separate lines unless the manual says otherwise.

Safety blocks at the start of a program usually include: G21/G20, G90/G91, G40, G49, G80, and a work offset (G54–G59). This resets the machine to a known state.

Example of a Complete Safety Block

O1000 (PROGRAM NAME: SAFE_START)
G21 G90 G40 G49 G80
G54
M09 M05 (Coolant off, spindle off)
M30

This block ensures that no leftover commands from a previous program interfere with the new job.

04Common Mistakes and How to Avoid Them

Based on real workshop experience, these errors happen frequently – especially to beginners.

MistakeConsequenceSolution
Forgetting G90/G91Tool moves to unexpected locationAlways specify absolute or incremental at program start
No G40 after cutter compNext operation uses wrong offsetCall G40 before tool change or end of program
Using G02/G03 without G17 (plane)Arc in wrong planeSet G17 for XY arcs, G18 for XZ, G19 for YZ
Missing M05 before M06Spindle may stop automatically, but not always – risk of crashExplicitly write M05 before every tool change
M08 left on at program endCoolant pump runs after job finishesAlways add M09 before M30

Real Case: A Simple Pocket that Crashed

A machinist once programmed a pocket using G01 for the first cut but forgot to cancel G41 (cutter compensation left) from a previous operation. When the machine moved to the next feature, it shifted the tool path by the radius value – cutting into a clamp. The solution: always include G40 in the safety block at the start of every program.

05Actionable Advice to Master G and M Codes

To become confident in CNC programming, follow these practical steps:

1. Memorize the top 10 G‑codes and top 8 M‑codes from the tables above. Write them on a cheat sheet and keep it near your machine.

2. Always start with a safety block that includes: G20/G21, G90, G40, G49, G80, G54. This eliminates hidden states.

3. Use a simulator before running on the machine – free tools like CNC Simulator or LinuxCNC’s preview mode let you test programs without risk.

4. Read existing programs from your machine’s memory. See how experienced programmers structure their code. Copy their patterns.

5. Verify every M‑code with your machine’s manual. While M03/M04/M05 are universal, some M‑codes (e.g., M07/M08) may be swapped or missing on different controllers.

6. Write a simple drilling or pocketing program by hand every day for one week. Start with a single hole,then add multiple holes, then a rectangle, then a circle. Repetition builds fluency.

06Summary: Core Points to Remember

G‑codes = motion and positioning (where and how the tool moves).

M‑codes = machine actions (spindle, coolant, stop, tool change).

Always start a program with a safety block to reset all modes.

Test every program with a simulator or single‑block mode on the machine.

Keep a reference table of common codes – you’ll memorize them quickly with practice.

Now you have a complete, actionable foundation in CNC G and M codes. Apply these principles to your next program, and you’ll avoid crashes, reduce setup time, and produce consistent parts.

YPMFG

Factory CNC Machined Parts

Need high-precision parts for your project? Get instant pricing & DFM feedback

Ready for Your Project?

YP-MFG is a leading manufacturer specializing in high-precision metal parts and CNC machining services.

Contact

WhatsApp/Phone

+86 137 9493 0097

Address

Building A6, The Third Industrial Zone, Fenghuang Community, Fuyong Street, Bao’an District, Shenzhen

Copyright YP-MFG © 2025 All Rights Reserved

滚动至顶部

Is your design ready for CNC machining?​

Upload your CAD file and discuss it directly with an experienced engineer.
Get a professional DFM review and full project consultation.