G and M-codes
G and M-codes
G and M-codes
G-code (also RS-274) is the most widely used computer numerical control (CNC) programming
language. It is used mainly in computer-aided manufacturing to control automated machine tools,
and has many variants.
G-code instructions are provided to a machine controller (industrial computer) that tells the motors
where to move, how fast to move, and what path to follow. The two most common situations are
that, within a machine tool such as a lathe or mill, a cutting tool is moved according to these
instructions through a toolpath cutting away material to leave only the finished workpiece and/or
an unfinished workpiece is precisely positioned in any of up to nine axes[1] around the three
dimensions relative to a toolpath and, either or both can move relative to each other. The same
concept also extends to noncutting tools such as forming or burnishing tools, photoplotting,
additive methods such as 3D printing, and measuring instruments.
Implementations
The first implementation of a numerical control programming language was developed at the MIT
Servomechanisms Laboratory in the late 1950s. In the decades since, many implementations have
been developed by many (commercial and noncommercial) organizations. G-code has often been
used in these implementations. The main standardized version used in the United States was settled
by the Electronic Industries Alliance in the early 1960s. A final revision was approved in February
1980 as RS-274-D. In other countries, the standard ISO 6983 is often used, but many European
countries use other standards. For example, DIN 66025 is used in Germany, and PN-73M-55256
and PN-93/M-55251 were formerly used in Poland.
Extensions and variations have been added independently by control manufacturers and machine
tool manufacturers, and operators of a specific controller must be aware of differences of each
manufacturer's product.
One standardized version of G-code, known as BCL (Binary Cutter Language), is used only on
very few machines. Developed at MIT, BCL was developed to control CNC machines in terms of
straight lines and arcs.
During the 1970s through 1990s, many CNC machine tool builders attempted to overcome
compatibility difficulties by standardizing on machine tool controllers built by Fanuc. Siemens
was another market dominator in CNC controls, especially in Europe. In the 2010s, controller
differences and incompatibility are not as troublesome because machining operations are usually
developed with CAD/CAM applications that can output the appropriate G-code for a specific
machine through a software tool called a post-processor (sometimes shortened to just a "post").
G-code began as a limited language that lacked constructs such as loops, conditional operators,
and programmer-declared variables with natural-word-including names (or the expressions in
which to use them). It was unable to encode logic, but was just a way to "connect the dots" where
the programmer figured out many of the dots' locations longhand. The latest implementations of
G-code include macro language capabilities somewhat closer to a high-level programming
language. Additionally, all primary manufacturers (e.g., Fanuc, Siemens, Heidenhain) provide
access to programmable logic controller (PLC) data, such as axis positioning data and tool data,
via variables used by NC programs. These constructs make it easier to develop automation
applications.
Specific codes
G-codes, also called preparatory codes, are any word in a CNC program that begins with the letter
G. Generally it is a code telling the machine tool what type of action to perform, such as:
There are other codes; the type codes can be thought of like registers in a computer.
It has been pointed out over the years that the term "G-code" is imprecise because "G" is only one
of many letter addresses in the complete language. It comes from the literal sense of the term,
referring to one letter address and to the specific codes that can be formed with it (for example,
G00, G01, G28), but every letter of the English alphabet is used somewhere in the language.
Nevertheless, "G-code" is metonymically established as the common name of the language.
Letter addresses
Some letter addresses are used only in milling or only in turning; most are used in both. Bold
below are the letters seen most frequently throughout a program.
Milling Turning
Code Description Corollary info
(M) (T)
G00 On 2- or 3-axis moves, G00
(unlike G01) traditionally
does not necessarily move in
a single straight line between
start point and endpoint. It
moves each axis at its max
speed until its vector quantity
is achieved. A shorter vector
usually finishes first (given
similar axis speeds). This
Rapid positioning M T matters because it may yield
a dog-leg or hockey-stick
motion, which the
programmer needs to
consider, depending on what
obstacles are nearby, to avoid
a crash. Some machines offer
interpolated rapids as a
feature for ease of
programming (safe to assume
a straight line).
G01 The most common workhorse
code for feeding during a cut.
The program specs the start
and endpoints, and the
control automatically
calculates (interpolates) the
intermediate points to pass
through that yield a straight
Linear interpolation M T line (hence "linear"). The
control then calculates the
angular velocities at which to
turn the axis leadscrews via
their servomotors or stepper
motors. The computer
performs thousands of
calculations per second, and
the motors react quickly to
each input. Thus the actual
toolpath of the machining
takes place with the given
feed rate on a path that is
accurately linear to within
very small limits.
G02 Very similar in concept to
G01. Again, the control
interpolates intermediate
points and commands the
servo- or stepper motors to
rotate the amount needed for
the leadscrew to translate the
motion to the correct tooltip
positioning. This process
repeated thousands of times
per minute generates the
desired toolpath. In the case
of G02, the interpolation
generates a circle rather than
a line. As with G01, the
actual toolpath of the
machining takes place with
the given feed rate on a path
that accurately matches the
ideal (in G02's case, a circle)
Circular interpolation, clockwise M T
to within very small limits. In
fact, the interpolation is so
precise (when all conditions
are correct) that milling an
interpolated circle can
obviate operations such as
drilling, and often even find
boring. Addresses for radius
or arc center: G02 and G03
take either an R address (for
the radius desired on the part)
or IJK addresses (for the
component vectors that
define the vector from the arc
start point to the arc center
point). Cutter comp: On
most controls you cannot
start G41 or G42 in G02 or
G03 modes. You must
already have compensated in
an earlier G01 block. Often, a
short linear lead-in
movement is programmed,
merely to allow cutter
compensation before the
main action, the circle-cutting
begins. Full circles: When
the arc start point and the arc
endpoint are identical, the
tool cuts a 360° arc (a full
circle). (Some older controls
do not support this because
arcs cannot cross between
quadrants of the cartesian
system. Instead, they require
four quarter-circle arcs
programmed back-to-back.)
G03 Circular interpolation, Same corollary info as for
M T
counterclockwise G02.
G04 Takes an address for dwell
period (may be X, U, or P).
The dwell period is specified
by a control parameter,
typically set to milliseconds.
Some machines can accept
either X1.0 (s) or P1000
(ms), which are equivalent.
Choosing dwell duration:
Often the dwell needs only to
last one or two full spindle
rotations. This is typically
Dwell M T much less than one second.
Be aware when choosing a
duration value that a long
dwell is a waste of cycle
time. In some situations, it
won't matter, but for high-
volume repetitive production
(over thousands of cycles), it
is worth calculating that
perhaps you only need 100
ms, and you can call it 200 to
be safe, but 1000 is just a
waste (too long).
G05 High-precision contour control Uses a deep look-ahead
M
P10000 (HPCC) buffer and simulation
processing to provide better
axis movement acceleration
and deceleration during
contour milling
G05.1 Uses a deep look-ahead
Q1. buffer and simulation
processing to provide better
AI Advanced Preview Control M
axis movement acceleration
and deceleration during
contour milling
G06.1 Activates Non-Uniform
Rational B Spline for
Non-uniform rational B-spline complex curve and waveform
M
(NURBS) Machining machining (this code is
confirmed in Mazatrol 640M
ISO Programming)
G07 Imaginary axis designation M
G09 Exact stop check, non-modal M T The modal version is G61.
G10 Modifies the value of work
Programmable data input M T
coordinate and tool offsets
G11 Data write cancel M T
G17 XY plane selection M
G18 ZX plane selection M T
G19 YZ plane selection M
G20 Somewhat uncommon except
in USA and (to lesser extent)
Canada and UK. However, in
the global marketplace,
competence with both G20
and G21 always stands some
chance of being necessary at
any time. The usual
minimum increment in G20
Programming in inches M T is one ten-thousandth of an
inch (0.0001"), which is a
larger distance than the usual
minimum increment in G21
(one thousandth of a
millimeter, .001 mm, that is,
one micrometre). This
physical difference
sometimes favors G21
programming.
G21 Prevalent worldwide.
However, in the global
marketplace, competence
Programming in millimeters (mm) M T
with both G20 and G21
always stands some chance of
being necessary at any time.
G28 Takes X Y Z addresses which
define the intermediate point
that the tool tip will pass
Return to home position (machine through on its way home to
M T
zero, aka machine reference point) machine zero. They are in
terms of part zero (aka
program zero), NOT machine
zero.
G30 Takes a P address specifying
which machine zero point to
use if the machine has several
secondary points (P1 to P4).
Takes X Y Z addresses that
Return to secondary home position
define the intermediate point
(machine zero, aka machine M T
that the tooltip passes through
reference point)
on its way home to machine
zero. These are expressed in
terms of part zero (aka
program zero), NOT machine
zero.
G31 Used for probes and tool
Feed until skip function M
length measurement systems.
G32 Similar to G01 linear
Single-point threading, longhand interpolation, except with
style (if not using a cycle, e.g., T automatic spindle
G76) synchronization for single-
point threading.
G33 Constant-pitch threading M
G33 Single-point threading, longhand Some lathe controls assign
style (if not using a cycle, e.g., T this mode to G33 rather than
G76) G32.
G34 Variable-pitch threading M
G40 Turn off cutter radius
Tool radius compensation off M T compensation (CRC).
Cancels G41 or G42.
G41 Turn on cutter radius
Tool radius compensation left M T compensation (CRC), left, for
climb milling.
Milling: Given righthand-
helix cutter and M03 spindle
direction, G41 corresponds to
climb milling (down milling).
Takes an address (D or H)
that calls an offset register
value for radius.
Turning: Often needs no D
or H address on lathes,
because whatever tool is
active automatically calls its
geometry offsets with it.
(Each turret station is bound
to its geometry offset
register.)
List of M-codes commonly found on FANUC and similarly designed controls for
milling and turning
Some older controls require M codes to be in separate blocks (that is, not on the same line).
Milling Turning
Code Description Corollary info
(M) (T)
M00 Non-optional—machine always stops on
Compulsory stop M T
reaching M00 in the program execution.
M01 Machine only stops at M01 if operator pushes
Optional stop M T
the optional stop button.
M02 Program ends; execution may or may not return
to program top (depending on the control); may
or may not reset register values. M02 was the
original program-end code, now considered
End of program M T obsolete, but still supported for backward
compatibility.[10] Many modern controls treat
M02 as equivalent to M30.[10] See M30 for
additional discussion of control status upon
executing M02 or M30.
M03 The speed of the spindle is determined by the
address S, in either revolutions per minute
(G97 mode; default) or surface feet per minute
or [surface] meters per minute (G96 mode
[CSS] under either G20 or G21). The right-
hand rule can be used to determine which
direction is clockwise and which direction is
Spindle on counter-clockwise.
M T
(clockwise rotation)
Right-hand-helix screws moving in the
tightening direction (and right-hand-helix flutes
spinning in the cutting direction) are defined as
moving in the M03 direction, and are labeled
"clockwise" by convention. The M03 direction
is always M03 regardless of the local vantage
point and local CW/CCW distinction.
M04 Spindle on
(counterclockwise M T See comment above at M03.
rotation)
M05 Spindle stop M T
M06 Many lathes do not use M06 because the T
address itself indexes the turret.
Programming on any particular machine tool
requires knowing which method that machine
uses. To understand how the T address works
Automatic tool T (some-
M and how it interacts (or not) with M06, one
change (ATC) times)
must study the various methods, such as lathe
turret programming, ATC fixed tool selection,
ATC random memory tool selection, the
concept of "next tool waiting", and empty
tools.[5]
M07 Coolant on (mist) M T
M08 Coolant on (flood) M T
M09 Coolant off M T
M10 Pallet clamp on M For machining centers with pallet changers
M11 Pallet clamp off M For machining centers with pallet changers
M13 This one M-code does the work of both M03
Spindle on
and M08. It is not unusual for specific machine
(clockwise rotation)
M models to have such combined commands,
and coolant on
which make for shorter, more quickly written
(flood)
programs.
M19 Spindle orientation is more often called within
cycles (automatically) or during setup
(manually), but it is also available under
program control via M19. The abbreviation
OSS (oriented spindle stop) may be seen in
reference to an oriented stop within cycles.
Example program
This is a generic program that demonstrates the use of G-Code to turn a part that is 1" diameter
by 1" long. Assume that a bar of material is in the machine and that the bar is slightly oversized
in length and diameter and that the bar protrudes by more than 1" from the face of the chuck.
(Caution: This is generic, it might not work on any real machine! Pay particular attention to point
5 below.)
Programming environments
G-code's programming environments have evolved in parallel with those of general
programming—from the earliest environments (e.g., writing a program with a pencil, typing it
into a tape puncher) to the latest environments that combine CAD (computer-aided design),
CAM (computer-aided manufacturing), and richly featured G-code editors. (G-code editors are
analogous to XML editors, using colors and indents semantically [plus other features] to aid the
user in ways that basic text editors can't. CAM packages are analogous to IDEs in general
programming.)
1. abandoning "manual programming" (with nothing but a pencil or text editor and a human
mind) for CAM software systems that generate G-code automatically via postprocessors
(analogous to the development of visual techniques in general programming)
2. abandoning hardcoded constructs for parametric ones (analogous to the difference in
general programming between hardcoding a constant into an equation versus declaring it
a variable and assigning new values to it at will; and to the object-oriented approach in
general).
STEP-NC reflects the same theme, which can be viewed as yet another step along a path that
started with the development of machine tools, jigs and fixtures, and numerical control, which all
sought to "build the skill into the tool." Recent developments of G-code and STEP-NC aim to
build the information and semantics into the tool. This idea is not new; from the beginning of
numerical control, the concept of an end-to-end CAD/CAM environment was the goal of such
early technologies as DAC-1 and APT. Those efforts were fine for huge corporations like GM
and Boeing. However, small and medium enterprises went through an era of simpler
implementations of NC, with relatively primitive "connect-the-dots" G-code and manual
programming until CAD/CAM improved and disseminated throughout the industry.
Any machine tool with a great number of axes, spindles, and tool stations is difficult to program
well manually. It has been done over the years, but not easily. This challenge has existed for
decades in CNC screw machine and rotary transfer programming, and it now also arises with
today's newer machining centers called "turn-mills", "mill-turns", "multitasking machines", and
"multifunction machines". Now that CAD/CAM systems are widely used, CNC programming
(such as with G-code) requires CAD/CAM (as opposed to manual programming) to be practical
and competitive in the market segments these classes of machines serve.[11] As Smid says,
"Combine all these axes with some additional features, and the amount of knowledge required to
succeed is quite overwhelming, to say the least."[12] At the same time, however, programmers
still must thoroughly understand the principles of manual programming and must think critically
and second-guess some aspects of the software's decisions.
Since about the mid-2000s, it seems "the death of manual programming" (that is, of writing lines
of G-code without CAD/CAM assistance) may be approaching. However, it is currently only in
some contexts that manual programming is obsolete. Plenty of CAM programming takes place
nowadays among people who are rusty on, or incapable of, manual programming—but it is not
true that all CNC programming can be done, or done as well or as efficiently, without knowing
G-code.[13][14] Tailoring and refining the CNC program at the machine is an area of practice
where it can be easier or more efficient to edit the G-code directly rather than editing the CAM
toolpaths and re-post-processing the program.
Making a living cutting parts on computer-controlled machines has been made both easier and
harder by CAD/CAM software. Efficiently written G-code can be a challenge for CAM software.
Ideally, a CNC machinist should know both manual and CAM programming well so that the
benefits of both brute-force CAM and elegant hand programming can be used where needed.
Many older machines were built with limited computer memory at a time when memory was
very expensive; 32K was considered plenty of room for manual programs whereas modern CAM
software can post gigabytes of code. CAM excels at getting a program out quickly that may take
up more machine memory and take longer to run. This often makes it quite valuable to
machining a low quantity of parts. But a balance must be struck between the time it takes to
create a program and the time the program takes to machine a part. It has become easier and
faster to make just a few parts on the newer machines with much memory. This has taken its toll
on both hand programmers and manual machinists. Given natural turnover into retirement, it is
not realistic to expect to maintain a large pool of operators who are highly skilled in manual
programming when their commercial environment mostly can no longer provide the countless
hours of deep experience it took to build that skill; and yet the loss of this experience base can be
appreciated, and there are times when such a pool is sorely missed because some CNC runs still
cannot be optimized without such skill.