g code on a screen for cnc machine

13 Useful G-Code and M-Code Commands You Might Not Know

Like most coding languages, G-code looks a bit weird when you first see it. There’s no apparent rhyme or reason, the numbers don’t seem to relate to each other, and the whole thing can appear a bit haphazard. It gets even stranger when you try to relate the codes themselves to the machines they work with. What do alphanumeric combinations have to do with x-y-z coordinate systems and toolpaths?

G-code programming is part of the firmware on all (or nearly all) machine tools. Lathes, mills, 3D printers – they’ll all have a machine controller with a native g-code language. While those languages can vary from manufacturer to manufacturer, they all follow the same general principles, and a majority of the actual codes remain the same.

What are G-Code commands?

G-code is a complex but simple programming language that uses Cartesian coordinate systems to tell a machine tool where to go and what to do with the workpiece. Each command begins with an alphanumeric combo or code that starts with G or M. By string together lines of g-codes, operators can automate the entire machining process, identifying work coordinates to ensure precise cuts.

G-codes are more than just “move here” and “cut this” commands. They include subprograms and subroutines (more on those later), as well as programs related directly to the machine itself. A lathe will have g-code commands to turn the spindle on and adjust spindle speed, while a milling machine with multiple tools will specify the tool number and tool length for each operation. 3D printers will have their own commands, like ones to heat the extruder to a designated temperature.

Individual G-code languages are typically available online and are open-source. Some, like the RepRap project for 3D printers, have been available for years, with commands

How many G-Code Commands are there?

The full list of G-codes runs to about a hundred commands, not including M-codes, subroutines, etc. For this article, we’ve selected 13 of the most common and most useful G-codes and M-codes for programmers, including some that may not be as familiar. For this article, we’ve selected 13 of the most common and most useful G-codes and M-codes for programmers, including some that may not be as familiar.

G-Code Commands

G20/G21 – Units Designation

Millimeters or inches? Use the G20 and G21 commands to select your unit of measurement. This needs to be done at the beginning of the program, otherwise, most machines will default to base settings or the previous program.

G0/G1 – Linear Movement

Move the tool from position A to position B. That’s the idea behind the linear move commands. Unsurprisingly, these are incredibly common commands found throughout most G-code programs; some estimates say that up to 90% of a given g-code program will consist of these straight-line moves.

The basic G-code move command will rely on a set of destination coordinates. Those coordinates (X, Y, and Z) specify where to finish the move.

G17/G18/G19 – Planar Selection

With these g-codes, operators can set the plane in which the rest of the commands will be executed. The X-Y plane (horizontal and vertical) is the default for most machines. But by designating an XZ or YZ plane, operators can achieve a slightly different range of operations.

G00 – Fast move

Fast move is straightforward; get the machine into position ASAP. It’s especially useful at the beginning or end of a program, or to reset the cutting head mid-way through. Note the current position, the end position, and let the rapid move take care of the rest.

G90 – Absolute Positioning

Many g-code commands rely on positioning – G0 X20 is a simple command to move the tool to a given coordinate on the X-axis. Absolute mode keeps things simple. There’s a set start point, and then X20 is 20 units down that axis. Absolute positioning is the default, but it does pose a challenge under certain conditions.

G91 – Relative Positioning

If the program relies on a series of actions that build on each other, relative positioning might prove helpful. rather than move to a pre-ordinated “X20” point, relative positioning instructs the machine to move 20 units from its previous position.

Most g-codes are modular – that is, they initiate an action that remains in effect until another action supersedes it. G90/91 are good examples. Specifying relative positioning cancels absolute positioning and vice versa.

G28 – Auto Home

Go home! The G28 command sends the tool back to where it all began. It’s useful both as a reset device, and to set the limits and parameters of the cutting area. Operators can specify a midpoint in the G28 command to clear obstacles.

G02/G03 – Clockwise and Counter-clockwise arcs

When using the G02 and G03 commands, you’ll need to specify a start point, end point, and a mid-point. That establishes all the parameters of the arc on the plane. You can perform an arc on any plane. Specify the x-axis, y-axis, or z-axis using the planar selection commands above.

G81-G89 – Canned Cycles

The picture is on the tin. Canned cycles are default mini-programs – you need to program certain parameters, but the basics of the program are pre-made. Canned cycles are mostly drilling cycles and boring cycles, including some threading operations. Using canned cycles speeds up the programming process and allows operators to copy/paste identical commands into different parts of the program.

M-Code Commands – Useful Interlopers

Most g-codes are standardized, at least for certain categories of machine tools. G-codes for milling machines should be broadly similar; the same with g-codes for lathes, 3D printers, and so forth.

M-codes are more complex. These are miscellaneous codes from the manufacturer – most of them vary widely from machine to machine, but there is a handful that stays consistent.

M00 – Program Stop

Want to run the program to a certain point then stop it completely for an inspection? M00 is the command for you. It shuts down the current operation and the machine itself, allowing you to change tools, rotate the part, clean the machine – whatever you need to do.

M06 – Tool Change

Operators for CNC machines with automatic tool changers use the M06 command to switch tools within the program. For machines that require a manual tool change, the M06 command usually indicates to the machine that there’s a new tool at work.

M01 – Optional Program Stop

If you might need to do a tool change, and you think you’d like a closer look at everything, then M01 is the right call. Insert an M01 command at regular intervals in your program to create potential checkpoints. Most CNC machines will have an optional stop button; press it, and the machine won’t shut down immediately. It will execute the program until it reaches the next M01 and then shut down.

M30 – Program reset/Return to start

M30 codes come in handy for continuous operation. They reset the program, telling the machine to go back to the beginning with the tool and start again.

A Code for All Seasons

There are dozens of other codes, used to specify spindle speed, set incremental moves, and identify or reset the home position and endstop for the tool. Each code has the potential to influence the rest of the program, particularly with modal codes that remain active until a new code supersedes them.

Other codes control how fast different actions are performed, such as feed rates, constant surface speed, and cutter compensation. Still, others set the length of time for certain operations, down to milliseconds.

Despite being apparently complex, a well-built g-code file contains everything the machine needs to conduct an operation without direct human intervention. 3D printing, 3D milling, and turning centers, and a huge range of other machine tools all rely on g-code commands.

You can find g-code programming tutorials online, from actual classes to informal YouTube training sessions. The specific g-codes mentioned above are standardized across machine tools, but you’ll need to look more closely at machine-specific lists to improve your skills.

About Peter Jacobs

Peter Jacobs is the Senior Director of Marketing at CNC Masters, a leading supplier of CNC mills, milling machines, and CNC lathes. He is actively involved in manufacturing processes and regularly contributes his insights for various blogs in CNC machining, 3D printing, rapid tooling, injection molding, metal casting, and manufacturing in general. You can connect with him on his LinkedIn.

Have Questions? Need a Quote?

Looking for more information about our CNC machines and services? Contact us today.


1 thought on “13 Useful G-Code and M-Code Commands You Might Not Know”

  1. You forgot the most important one:
    I print to my Ender 3v2 via USB from my computer, using Cura…and the Cura controls don’t include one for “unlock steppers”, so I had to unlock the steppers via the control panel whenever, for instance, I wanted to manually level the bed.
    Then I looked up the M-code for unlocking it. Saves me valuable milliseconds.

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Slide 1

MX Software – Easy to Use, Easy to Learn – Included with your machine purchase
The MX software is designed to work seamlessly with your CNC Masters machine. It is made to work with Windows PC – desktop, laptop, or an all in one – on standard USB. Use it on Windows 8 or 10 64-bit operating systems.
No internal conversion printer/serial port to USB software or additional conversion hardware is used with the MX.

Slide 1

2. Clutter Free Interface
The MX is engineered for the CNC MASTERS machine so you do not have to fiddle with a detailed complicated configuration that can be overwhelming. Just load in the MX and start machining!2. Clutter Free Interface
The MX is engineered for the CNC MASTERS machine so you do not have to fiddle with a detailed complicated configuration that can be overwhelming. Just load in the MX and start machining!

Slide 1

3. Features Tour and Tutorials Included
The Features Tour will give you a quick run-down on all the features the MX can do for you. The Tutorials are easy to follow even for the first time CNC machinist.
Feel free to download the MX on any of your computers. We recommend downloading the MX along with your CAD and CAM software there at the comfort of your office computer to generate your tool path programs. You don’t need to be hooked up to the machine either to test your program in simulation mode.

Slide 1

4. Navigate and Edit Your Program through the MX interface with Ease
With a few clicks of the mouse or using touch screen technology, you can easily navigate through the MX interface importing saved programs into the Editor from the File drop down menu. Using standard windows features to edit your program you can then lock the Editor Screen to avoid accidental editing, and if you need to insert a line in the middle of a program, just click on [ReNum] to re-number your tool path list.
You can create a program or import CAM generated G-code tool paths into the Editor
The X Y and Z W arrow jog buttons are displayed from the point of view of the cutter to avoid confusion when the table and saddle are moving. You can also adjust your spindle speed and coolant control while jogging each axis.

Slide 1

5. Feed Hold – Pause in the Middle of your Program
Feed Hold lets you pause in the middle of a program. From there you can step through your program one line at time while opting to shut the spindle off and then resume your program.
You can also write PAUSE in the middle of your program and jog each axis independently while your program is in pause mode.

Slide 1

6. Hot Keys
Hot Keys is an alternative method to easily control your machine using your hard or touch screen keyboard. One can press P to pause a program, press S to turn Spindle On, G to run a program, Space Bar to Stop, J to record your individual movements one line at a time to create a program in teach mode.

Slide 1

7. Pick Menu – for conversational mode programming
Write FANUC style G-codes directly into the Editor or select commands off the [Pick] menu and write your tool path program in conversational mode such as what is written in the Editor box. You can even mix between conversation commands and G-codes in the same program.

Slide 1

8. Pick Menu List of Options
Use commands such as MOVE, SPINDLE ON/OFF, COOLANT ON/OFF, PAUSE, DELAY, GO HOME…. to write your tool path programs in conversational mode.

Slide 1

9. Draw the Tool Path to verify it before pressing Go
Hit Draw to view your tool path program drawing, check out its run time, or even simulate the tool path in 3D mode. This can be helpful to quickly verify your program before running it. You can also slow down or speed up the drawing or simulation process.
You can also hit Go within the Draw Window itself to verify the cutter’s position on the machine. The current tool path will be highlighted and simultaneously draw out the next path so you can verify what the cutter will be doing next on the program.

Slide 1

10. Run each tool path independently to study its movement
1. Run the machine on Trace mode. You can run each tool path independently, one line at a time to study the tool path movement on the machine to verify the position of the application and if any fixture/vise is in the way of the cutter’s path.

2. You can also verify your program by clicking on the Trace and Draw buttons together. This will allow you to view each tool path independently one line at a time in the Draw Window.

Slide 1

11. Counters display in Inches or Millimeters – Continuous Feed
1. When running a program, the counters will display a “real-time” readout while the machine is in CNC operation without counting ahead of the movement.
2. The current tool path is highlighted while the machine is in operation without causing slight interruptions/pauses as the software feeds the tool path to the machine. The MX internally interprets a program ten lines ahead to allow for “continuous machining” avoiding slight interruptions as the machine waits for its next tool path command.
3. “Run Time” tells you how long it takes to run your tool path program.

Slide 1

12. Use the “Go From Line” command to start in the middle of your program
If you ever need to begin your program from somewhere in the middle of it, use [Go From Line] which you can find under Tools. The Help guide will walk you through how to position the cutter without losing its position on the machine.

Slide 1

13. Exact Motion Distance without over-stepping on an axis while jogging
Use “Relative ON” to enter a specific coordinate to jog any of your axes to an exact location without having to write a program. It’s like using “power feed” but easier. You can jog an exact distance on any of the axes without needing to keep the key pressed down and mistakenly over-step the movement releasing your finger too slowly off the jog button.
Let’s say you need to drill a hole exactly 0.525” using the Z. So you enter 0.525 in the Z box. Next, adjust the JOG FEED RATE slider for the desired feed rate. Then “click once” on the +Z or -Z button to activate the travel. In this case you click once the -Z button first to drill the hole exactly 0.525”. Then click once on the +Z button to drive the axis back up 0.525”.

Slide 1

14. Teach Mode – Jog Input
You can create a tool path program by storing each point-to-point movement by simply jogging an axis one at a time. Click on either of the Jog Input buttons to store each movement on the Editor Screen. You can then add Spindle ON, feed commands, and press GO to run the new program as needed. This is a great feature to help you learn to create a program by the movements you make on the machine without necessarily writing out an entire program first.

Slide 1

15. Override on the fly to adjust the Jog Feed to Rapid or the Spindle Speed during the middle of a program
1. Jog Feed and Rapid with Override: You can adjust feeds using the slider from slow minimum 0.1″ per minute to a rapid of 100″ per minute of travel. You can even micro-step your jog as low as 0.01”/min. The [-][+] buttons allow you to fine tune feeds in 5% increments while the program is in motion.
2. Spindle Speed with Override: You can adjust speeds using the slider from a slow minimum RPM to the max RPM according to the machine setup. The [-][+] buttons allow you to fine tune feeds in 5% increments while the program is in motion.

Slide 1

16. Adjust Counters using Pre-Set if you cannot begin the program from 0.00
In a situation where you cannot begin your cutter at it’s 0.00 location, you can “Pre-Set” directly into the counters by typing in your beginning coordinate. You can press Go from here to run your program. You can also “zero all” or “zero” your counters independently. With one click of the [Return to 0.0] button, all axes will travel back to its respective 0.0 on the machine.

Slide 1

17. Set and Save your 0.00 position for future runs
Set and save your 0.00 position on the machine. These coordinates will be recorded as the first line of the program in the Editor Screen. Should you desire to return to this program at a later date, you only have to click on the Set Zero Return button. This will command the machine to automatically jog each axis to its saved “set” 0.00 position according to the recorded coordinates at the first line of the program.

Slide 1

18. Create a “Home” position to clear your application and run multiple times
Let’s say you need to machine one application times 100 pieces. This usually requires a jig to retain that physical 0.00 position. But in this case, you want the program to end with a clearance of the axes to easily switch out the next piece of stock and start again. With Save Home, you have the ability to save this offset (home) position while still retaining your Set Zero position where the machine will mill your part out. Pressing [Save Home] will record this new position under the Set Zero line in your program.
Pressing [Go Home] will jog your axes back to your “saved home” position where you originally pressed the Save Home command. You can also input GO_HOME from the Pick Menu as its own tool path in your program. At the completion of your program the axes will end at your Home position. Replace your part, then press [Return to 0.0] button to allow the axes to return to its zero position, and press Go to start your next run.

Slide 1

19. Disable the axis motors to manually hand crank each axis into place
Easily de-energize the axis motors by clicking [Disable Motors] to crank each axis by hand, and then press [Reset Control] to re-energize the axis motors.

Slide 1

20. Change up to 30 tools with compensation, and store your tool offsets for other programs
The MX supports…

Slide 1

21. Use the optional ATC rack up to 8 tools for milling, drilling, and rigid tapping applications
The CNC Masters Automatic Tool Changer Rack and Tools (US Patent 9,827,640B2) can be added to any CNC Masters Milling Machine built with the rigid tapping encoder option. The tutorial will guide you through the set-up procedure using the ATC tools.

Slide 1

22. Use the optional Rigid Tapping Wizard without the need for tapping head attachments
When you order your CNC Masters machine, have it built with the optional rigid tapping encoder. You can take any drill cycle program and replace the top line with a tapping code created by the wizard to tap your series of holes up to 1/2” in diameter.

Slide 1

23. Use the optional Digital Probe to scan the profile and/or pockets of your fun/hobby type designs to write your tool path program and machine out a duplicate of your original design To “surface” scan an object, you can program the probe along the X or Y plane. The stylus will travel over the part starting on the left side front corner of the object and work its way to the end of the part on the right side. Depending on how the stylus moves, it will record linear and interpolated movements along the X, Y, and Z planes directly on the MX Editor.
To “pocket” scan an object containing a closed pocket such as circles or squares, the scan will start from the top front, work its way inside of the pocket, and scan the entire perimeter of the pocket.
Under the Setup of the MX software you will find the Probe Tab which will allow you to calibrate and program your probe. Your “Probe Step”, “Feed”, and “Data Filter” can also be changed on the fly while the probe is in the middle of scanning your object.

Slide 1

24. Use work offsets G54-G59 for nesting applications
The work offsets offer you a way to program up to six different machining locations. It’s like having multiple 0.0 locations for different parts. This is very useful especially when using sub-routines/nesting applications.

Slide 1

25. Create a Rectangular Pocket / Slot with our selection of Wizards to help you build a tool path program
The Cycle Wizards for the mill or lathe makes it easy to create a simple tool path without needing to use a CAD and CAM software.
On this Wizard, the Rectangular Pocket / Slots, can be used to form a deep rectangular pocket into your material or machine a slot duplicating as many passes needed to its total depth.

Slide 1

26. Create a Circular Pocket Wizard
Input the total diameter, the step down, and total depth and the code will be generated.

Slide 1

27. Do Thread Milling using a single point cutter Wizard

Slide 1

28. Cut a gear out using the Cut Gear Wizard with the optional Fourth Axis

Slide 1

29. Create a Peck Drilling Program in Circular or Rectangular Patterns
Using the Circular or Rectangular Drilling Wizards, you can program the machine to drill an un-limited series of holes along the X and Y planes. Program it to drill straight through to your total depth, use a high-speed pecking cycle, or deep hole pecking cycle. You can program the cut-in depth and return point for a controlled peck drill application to maximize chip clearance.

Slide 1

30. The MX interface can easily be interchanged from Mill Mode to Lathe Mode
Use this interface for your CNC Masters Lathe. It contains all the same user-friendly features and functions that comes in Mill Mode. Simply go to the Setup page and change the interface.

Slide 1

31. Use Tool Change Compensation or the optional Auto Tool Changer Turret if your application requires more than one tool in a single program
You can offset the length and angle of each tool and record it under Tools in your Setup. The program will automatically pause the lathe’s movement and spindle allowing you to change out your tool, or allowing the optional ATC Turret to quickly turn to its next tool and continue machining.
On the MX interface, you also have four Tool Position buttons. Select your desired T position, and the auto tool post will quickly turn and lock itself to that position.

Slide 1

32. Use the Lathe Wizard Threading Cycle to help you program your lathe’s internal or external threads in inches or metric

Slide 1

33. Use the Lathe Wizard Turning / Boring Cycle to help you program simple turning and boring cycles without having to go through a CAM or writing a long program with multiple passes

Slide 1

34. Use the Lathe Wizard Peck Drilling Cycle to help you program your drill applications or for face grooving

Slide 1

35. Facing / Grooving / Part Off Cycle Wizards – with Constant Surface Speed
These cycles can be used with Constant Surface Speed allowing the spindle speed to increase automatically as the diameter of the part decreases giving your application a consistent workpiece finish. With CSS built into the wizard, there is no need to break down the cycle into multiple paths and multiple spindle speed changes.

Slide 1

36. This is our list of supported G and M codes which can be found under Tools > G Code/ M Code List in the MX
If you plan to use a third-party CAM software to generate your tool path program, use a generic FANUC post processor and edit it to match our list of codes. As an option, we also sell Visual mill/turn CAM software which comes with a guaranteed post processor for our machines to easily generate your tool path programs based on your CAD drawings.

Slide 1

37. Our pledge to you…

previous arrow
next arrow