What is G and M Code in CNC Machining ?

by | Apr 23, 2022

Computer Numerical Controlled (CNC) machines are highly advanced units that can machinie metal and plastic components without much labor involvement. This degree of automatization requires some programming, so the equipment units have commands to follow.

G and M code are exactly the languages that are used to program manufacturing operations. Let’s examine them in detail and compare them to each other. There also will be a review of specific instructions that you can write using G and M code and a tutorial on how to learn them.

To be precise, G and M codes are programming languages that are used to write sequences of instructions that CNC machine can read and execute.

What is G Code in CNC?

G code is the language that has the alphanumeric format and can be used to manipulate the geometry of a CNC machine’s movable parts, like spindles. It is used to indicate what cutting tool to move, across which axis, how fast the movement should be, when to stop the tooling, etc. There are called cutting-related functions of the equipment. Or any other performance functions, like extrusion in 3D printing

The basic structure of a G-coded command is a letter that defines a command type, a number that follows a letter and defines a command subtype, and a sequence of coordinates that regulate the movement of a movable part. You can see an example of a code for a 3D printer in the image below.

G code for 3d printer

Once you have an initial insight into the general appearance of the code, let’s review what letters mean first:

  • N – determines the line number. 
  • G – define the start and stop of a performance tool. 
  • X, Y, Z – coordinates that indicate the position of a performance tool in three dimensions, which are horizontal, vertical, and depth respectively.
  • F – indicates the needed feed rate of a performance tool.
  • S – indicates the movement of a performance tool along an axis.
  • T – indicate what exact tool exactly is to be used to complete the following commands.
  • I and J – indicate the incremental center of an arc.
  • R – defines the radius of an arc.
  • A – is a direction of a performance tool along the X-axis.
  • B – is a rotation of a performance tool along the Y-axis.
  • C – is a positional value of an auxiliary axis rotating along the Z-axis.
  • D – offsets the tool diameter by the system.
  • L – indicates a value for repeating operations; define a number of repetitions in the loop.
  • P – define time jump or time delay.

It is important to mention that all CNC machines understand instructions written in this programming language. But different equipment units, especially ones that fulfill distinct manufacturing operations, do comprehend the same commands somewhat differently. That’s why there will be certain command specificities, like a number of zeros between letters, spaces between commands, etc, that depend on the unit type.

What is M Code in CNC?

Actually, the M letter could be included in the previous section already, as it is a subtype of G code. But since it is a unique part of the programming language, it is paid particular attention. M gives ON and OFF orders, making one or another function of a CNC unit start or stop working, respectively.

Basically, any specific functions like changing tools, flooding the unit with coolant, and starting and stopping, are defined by the M code. So it is fully responsible for all the non-cutting, or rather non-direct performance operations. 

In contrast to G code, M code, like any subtype, has generic values that indicate the command to be performed. The most important of them, which are usable for any CNC machine, are the following:

M code in CNC machining
  • M00 – Full stop of all the operations being performed.
  • M01 – An optional operation stop.
  • M02 – End of a particular operation being performed.
  • M03 – Moving a performance tool clockwise.
  • M04 – Moving a performance tool anticlockwise or reverse.
  • M05 – Stop moving a performance tool.
  • M06 – Load another performance tool.
  • M06 – Turn the coolant on.
  • M08 – Start flooding with coolant.
  • M08 – Stop flooding with coolant.

It is essential to know that the M code is not a distinct part of the complete program for a CNC machine. It is integrated into the list of commands within lines of G code so they both regulate each minor action for a machine to perform. So you should know them both to code the CNC programs manually.

Differences Between G and M Codes

The way G and M coding are similar or different may already be evident. But let’s summarize everything to never confuse them for sure.

FactorG codeM code
TypeGeometric/preparatory codeMachine/Miscellaneous code
PurposeRegulation of all the direct performance actions, movements, and positions.Regulation of all the non-direct performance actions.
Adjustment for a specific CNC machine neededNearly any basic command may differ depending on the equipment unit type.Most basic commands are universal for all the unit types. But all the machines have their unique M code commands additionally.
Executive approachSetting cyclic machining movementsTurning ON and OFF a specific function

How G and M Codes are Implemented?

Any manufacturing process starts with a preparation of a digital 3D model – prototype. It serves the purpose of representing a future component. It is created by an engineer or a designer, or both, using computer-aided design software. In case you are already curious what are the concrete examples to download and give a try, here is the list:

  • FreeCAD – an open-source, free-to-use tool for designing objects of any complexity in real-time.
  • TinkerCAD – an intuitive, user-friendly tool for beginners that allows the building of simple objects.
  • AutoCAD – is one of the first such software to be ever released. It aims at experts and is ideal for 2D objects or extremely intricate 3D objects.
  • Fusion 360° – a cloud-based CAD software that enables teams of developers to collaborate on design projects.

While only several CAD digital tools are listed, be sure that there are many more similar options on the market. Some of them allow creating only simple designs. But others may even have a library of different materials to attribute to a part. Or have the capacity to construct an object with real dimensions, which is incredibly useful. There are software solutions that even have a CAM feature integrated.

Referring to computer-aided manufacturing (CAM) software, it is another absolutely necessary digital tool. It is completely G and M code-based and allows automation of the porting process. Or, in other words, it allows converting a CAD object to a CAM file, that a CNC unit can potentially read and execute. 

CAM software scans your 3D model and ports it to a small-sized document that contains an approximate sequence of instructions that a given CNC unit should perform to cut a 3D, solid component from a workpiece. But it is a really complicated process indeed. And you almost never get the desired result that would require no manual coding and error fixing. And here are the reasons why:

  • Consideration of an equipment unit. The primary problem is that you do not have much of a choice for which machine a program is written. It means that you, for instance, may have an advanced 6-axis CNC router fully capable of performing entire machining independently. But the CAM software generates the program intended for a manufacturing line comprising 2-3 equipment units with 3-axis each. Or vice versa.

The CAM software cannot produce a program intended for a particular CNC machine. So, you naturally need to revise the program. Split it, or combine distinct sets of G and M-coded instructions so your units can perform it. 

  • Considerations of a material. In another example, you receive a wrong program that does not perform well because it is intended for stainless steel as an option. But you intend to cut wood. And basically, the chosen feed rate and other metrics, tools, and actions do not suit your purposes.

This way, you will also need to adjust the program manually so it better reflects your choice of material.

  • Technical errors. Every software and any machine cannot perform error-free, and CAM digital tools are no exception. A program may unpredictably recognize some elements of your model incorrectly. It may result in generating contradictory instructions that would not enable complete machining. Any other machine processing errors may occur as well.
  • The incorrectness of a 3D model. Finally, it may be just that you modeled a component in a way it cannot be correctly scanned. For example, indicated dimensions are wrong, or elements are placed in a way it cannot be machined in real life. Even if your CAM software somehow processed the model, you still will have much work fixing the G and M code yourself.

In case you are not scared of the mentioned challenges of using CAM software, here are some popular tools to employ:

  • OpenBuilds CAM – a web-based and completely free program that supports most CAD software’s file types and a wide array of CNC equipment units.
  • Inkscape Laser Plug-In – an effective tool intended specifically for laser CNC machines. 
  • Estlcam – another specialized software that offers superior coding precision for milling programs.
  • FreeMill – a great CAM software intended for both beginners and experts that require G and M-code exporting with post-processing options included.

So, there are applications that do facilitate G and M coding. But, you still need at least basic knowledge of these programming languages to ensure the correctness of the automatically generated instructions.

How does CNC Programming Control CNC Machines?

In case you wonder how exactly programs written in G and M code languages control CNC machines, here is a simple explanation. 

Since manufacturing units are numerically controlled, they can “read” input instructions generated with the use of symbols that such machinery is programmed to understand. So, all the basic functions for a CNC machine to perform are already inserted in it. And all you actually do is refer to these predefined commands so the machine knows which action to do in a specific moment of time.

At the same time, the software of the machine sends electronic signals to motorized, maneuverable tools of a machine – spindles. Or extruders, in the context of 3D printing. This way, separate motors make any of the movable parts perform the commanded action.

All the programs are basically sets of cyclic instructions. They define how a CNC unit must proceed with a particular workpiece, return to an initial position, wait till the next workpiece is mounted, and repeat the entire set again. 

Such machinery does not have an AI-based computer vision, so it is the responsibility of the technicians to adjust each program, so it is fulfilled correctly with particular tools and over specific materials. 

G Code and M Code Commands List

You need a library of the commands regardless of the software you intend to employ or the method you will be learning G and M codes with. Use the following tables of commands to construct basic programs.

G Codes

G00MotionMove in a straight line at rapid speed.
G01MotionMove in a straight line at last speed commanded by a feedrate
G02MotionClockwise circular arc at feedrate
G03MotionCounter-clockwise circular arc at feedrate
G04MotionDwell: Stop for a specified time.
G05MotionFADAL Non-Modal Rapids
G09MotionExact stop check
G10CompensationProgrammable parameter input
G15CoordinateTurn Polar Coordinates OFF, return to Cartesian Coordinates
G16CoordinateTurn Polar Coordinates ON
G17CoordinateSelect X-Y plane
G18CoordinateSelect X-Z plane
G19CoordinateSelect Y-Z plane
G20CoordinateProgram coordinates are inches
G21CoordinateProgram coordinates are mm
G27MotionReference point return check
G28MotionReturn to home position
G29MotionReturn from the reference position
G30MotionReturn to the 2nd, 3rd, and 4th reference point
G32CannedConstant lead threading (like G01 synchronized with spindle)
Tool cutter compensation off (radius comp.)
Tool cutter compensation left (radius comp.)
Tool cutter compensation right (radius comp.)
Apply tool length compensation (plus)
Apply tool length compensation (minus)
Tool length compensation cancel
Reset all scale factors to 1.0
Turn on scale factors
G52CoordinateLocal workshift for all coordinate systems: add XYZ offsets
G53CoordinateMachine coordinate system (cancel work offsets)
G54CoordinateWork coordinate system (1st Workpiece)
G55CoordinateWork coordinate system (2nd Workpiece)
G56CoordinateWork coordinate system (3rd Workpiece)
G57CoordinateWork coordinate system (4th Workpiece)
G58CoordinateWork coordinate system (5th Workpiece)
G59CoordinateWork coordinate system (6th Workpiece)
G61OtherExact stops check mode
G62OtherAutomatic corner override
G63OtherTapping mode
G64OtherBest speed path
G65OtherCustom macro simple call
G68CoordinateCoordinate System Rotation
G69CoordinateCancel Coordinate System Rotation
G73CannedHigh speed drilling cycle (small retract)
G74CannedLeft hand tapping cycle
G76CannedFine boring cyle
G80CannedCancel canned cycle
G81CannedSimple drilling cycle
G82CannedDrilling cycle with dwell (counterboring)
G83CannedPeck drilling cycle (full retract)
G84CannedTapping cycle
G85CannedBoring canned cycle, no dwell, feed out
G86CannedBoring canned cycle, spindle stop, rapid out
G87CannedBack boring canned cycle
G88CannedBoring canned cycle, spindle stop, manual out
G89CannedBoring canned cycle, dwell, feed out
G90CoordinateAbsolute programming of XYZ (type B and C systems)
G90.1CoordinateAbsolute programming IJK (type B and C systems)
G91CoordinateIncremental programming of XYZ (type B and C systems)
G91.1CoordinateIncremental programming IJK (type B and C systems)
G92CoordinateOffset coordinate system and save parameters
G92 (alternate)MotionClamp of maximum spindle speed
G92.1CoordinateCancel offset and zero parameters
G92.2CoordinateCancel offset and retain parameters
G92.3CoordinateOffset coordinate system with saved parameters
G94MotionUnits per minute feed mode. Units in inches or mm.
G95MotionUnits per revolution feed mode. Units in inches or mm.
G96MotionConstant surface speed
G97MotionCancel constant surface speed
G98CannedReturn to initial Z plane after canned cycle
G99CannedReturn to initial R plane after canned cycle

M Codes

M00M-CodeProgram Stop (non-optional)
M01M-CodeOptional Stop: Operator Selected to Enable
M02M-CodeEnd of Program
M03M-CodeSpindle ON (CW Rotation)
M04M-CodeSpindle ON (CCW Rotation)
M05M-CodeSpindle Stop
M06M-CodeTool Change
M07M-CodeMist Coolant ON
M08M-CodeFlood Coolant ON
M09M-CodeCoolant OFF
M17M-CodeFADAL subroutine return
M29M-CodeRigid Tapping Mode on Fanuc Controls
M30M-CodeEnd of Program, Rewind and Reset Modes
M97M-CodeHaas-Style Subprogram Call
M98M-CodeSubprogram Call
M99M-CodeReturn from Subprogram

How to Learn G and M CNC Codes?

In case you intend to fabricate components using a CNC unit, you naturally need some G coding skills.

Basic Programming

Here is a basic program structuring overview:

  • Definitions statements. The program starts by defining the origin, i.e., from where you need a CNC unit to start machining, what the performance tool is, and what its settings are. Such statements also include settings for tooling. For example: N003 G94 (feed rate in mm/min); N006 M06 T01 (tool selection); 
  • Machining statements. Then, you set the coordinates to which a performance tool will be moving along axes. For example: G0 X0 Y0 (moving to origin point); G00 X75 (moving to point one located in 75 mm along the horizontal axis);
  • Closing statements. Finally, you write commands that tell a machine that the program is ended, and return tools to their original position and settings to their initial states. For example: N019 G91 G28 Z0 (Home Position); N021 M05 M09 (spindle off, and coolant off);

Tips and Advice You Need to Know

And here are the useful recommendations on how to learn and implement coding successfully:

  • Know your CNC unit. It is especially significant to use the correct commands intended for a particular equipment unit. So be sure to consider the type of your machinery, number of axes, and even a supplier’s brand while searching for appropriate commands via libraries.
  • Ask a supplier. It is not difficult to find most of the basic commands on the Internet. But a manufacturer may integrate extra functions into its equipment unit. So it is always a good idea to ask for a list of all the commands programmed.
  • From simple to complicated. Start with modeling, converting, and manually fixing the most simple programs, preferably for 2D components. Most of the definitions and closing statements are the same for most units and programs. So you need to learn them first. And then, you will be fully capable of deepening into intricate designs that require complex machining statement writing.
  • Use templates. You may search for the prepared programs for your CNC machine. They may have definitions and closing statements and some M coding written. This way, you can fix errors in the automatically converted programs or simplify the manual coding.

G code and M code are the basic for CNC machining. If you can understand the meaning and how to set for each command, you can apply for the CNC operator job in the market. Anybode has other questions about G and M codes in CNC machinie, you can feel free to contact us.

Need Any Services? Contact Us Now!

    Subscribe To Our Newsletter

    The lastest metal machining and 3d printing post delivered to your inbox.