G-code, or Geometric Code is a simple, powerful and flexible open source programming language, built to drive machines – cutting machines, positioning systems and robots.
It was created to provide:
- Location in Cartesian (linear 3D) space
- Actions during and after motion
- Ancillary controls for machine functions
The language is mostly used for CNC (Computer Numerical Control) machine tools to tell them:
- What tool to use
- Where and how to move it
- How fast to rotate it; where and how to cut
Although G-code was developed for CNC machine tools, the family of CNC has grown, and G-code has adapted to suit other classes of machine.
3D printers and functional robotics use this language, but it has also integrated polar coordinates.
G-code is the most widely employed language for programming CNC machines. Orthogonal X-Y-Z, tool and workpiece rotational and sometimes polar coordinates instruct position for the driven axes, additional commands control spindle, tool change, coolant pumps etc. The automation of CNC processes is entirely defined in their G-code programming.
History and Background
Machine tools have a long history.
Devices such as the Antikythera Mechanism suggest precision that likely had machine aspects. Wood lathes date to 300BC in Egypt. Potters wheels are much older.
But the pace of development has accelerated since the Vaucanson lathe in 1751, the Guilloche Linear Engine, the Jacquard Loom (punch card programming) in 1801, the Whitney Milling Machine in 1818, the Punch Card Bridgeport Mills of the 1950s, the first CNC machines from the MIT Servomechanisms Lab in the late 1950s, and the explosion of automation since.
G-Code was developed to drive the first CNC machines at MIT.
It was a simple approach that sequenced move and switching commands – readable and directly editable by experienced users. Its minimalist simplicity made it an enduring tool.
G-Code is likely now the most commonly used programming language in the world, and perhaps the only early language that remains important.
From laser cutters to cake decorating, from milling machines to fabric cutting, machines driven by G-Code programming automate making.
How G-code works?
G-Code is a language of commands that are executed in sequence.
Net shape extraction of a part is the result of step by step execution of commands.
Interpretations of the part and the material can result in different toolpaths, making programming a skilled task that has significant effect on quality of outcome.
CAM software is improving rapidly, but still it is unlikely that an automated system will optimize the toolpath, for a non-simple part.
There are too many variables, so it requires intelligence and experience to achieve the best results.
CAM is also optimized for maximum safety and machine tool life, which translates as slow throughput.
The G-Code commands encompass
- Current position
- ‘Zero’ referencing to confirm open loop position by return to origin
- Travel commands at full speed and at controlled speed for single axes
- Travel/feed commands for multiple axes, to create curvature in 2D and 3D and to allow efficient obstacle avoidance while minimizing path length
- Startup and stop commands to control acceleration and deceleration
- Spatial references for obstacles that must be avoided
- Tool change commands
- Spindle speed and acceleration/deceleration commands
Additional commands that are specific to classes and manufacturers of machines comprise an element of the language.
Though they’re often referred to as M-Code (machine type specific instructions), they’re not really separate, but an additional layer of language to control specialist aspects.
G-Code Is Generated in 2 ways
- CAM (Computer Aided Manufacturing) software can generate the G-Code from 2D or 3D CAD. This works well for simpler applications and for mass production of ranges of related parts, where the CAM setup can be precisely tuned to the typical components and to the material/machine conditions.
- Code can be written directly by an operator/programmer. For simple use cases, an inexperienced programmer can learn a great deal by writing and executing code in this way. For more complex parts, this can be a long and intricate process, and it is increasingly unusual to see CNC programming done in this way.
With a new program written/CAM generated it is normal to test it for gross failures (impacts, overspeed, cutter selection errors etc.) by running a simulation and then a dry run on the machine.
Simulation is virtual, dry run is with cutters but no material in place. Many CAM packages include a simulation package that will provide a 3D visualization of the toolpath and often offer diagnostics for the likely accuracy, quality, and feasibility of the proposed cutting process.
The characteristics of the machine the code is to run on must be right – factors like axis limits, clamping and workpiece obstructions, tool changer positions etc. These factors are often partly pre-loaded in the CAM/simulation software, but must be validated to avoid breakages.
G-Code, by which we mean the direct writing and editing of machine instructions, has a number of key use cases:
- For simple geometrical parts, there is often no advantage in designing in CAD, the required toolpath can be directly written to the CNC machine. This cuts out a lot of modeling and software handling steps and can speed up the process considerably.
- Checking CAM output. However good the CAM software, there is always the potential for toolpath bugs. A modest level of experience can equip the machine operator to run a simulation and make manual edits to correct problems before they become metal and impact.
- When you go to set up the machine to run the code your CAM has generated, that you’ve simulated and revised, you discover the tool setups are wrong. Adjusting cutter lengths, or diameters is a simple task, directly in the G-Code, when you know what you’re doing – no need to cycle back through CAM to make the change.
- Same when you dry run or first off run the code – errors are always possible, and direct editing of the G-Code allows efficient corrections to be made without cycling back to CAM software to the CAD model.
- Alterations in toolpath to reduce wasted motion or increase speeds/accelerations where these will not disrupt the outcome quality.
- Routine utilities like machine warm up, standardized block squaring and face prep, zeroing wear offsets and repetitive manual tasks can all be set up as G-Code routines that are ready to call up as needed.
Usage and Examples
The list of industries that employ G-Code programmed CNC (and other) machines is the list of all industries.
CNC programming is generally performed in G-Code either directly or through CAM software. The versions of the language apply to a wide family of industrial equipment, wherever a machine requires cartesian or polar navigation followed by a function while moving or on arrival at the specified coordinates.
The use of CNC machined and CNC laser cut parts is very widespread.
This is a function of relative price insensitivity and the need for exacting standards and certifications, for life critical components.
Specialist suppliers with appropriate certifications from reputable quality standards organizations are able to compete effectively, generally competing on quality of service and facilities/skills, rather than on price.
Aircraft skin components are commonly laser cut, which is generally a CNC process operating by G-Code.
Frame and control components are often cast/forged and then CNC machined on multi axis machining centers, at high precision.
Medical/dental implants and equipment
Various implant components and internal/external devices are used across the medical sector.
Much like in aerospace, there is low sensitivity to price but very high sensitivity to quality and certification issues.
Patient implants have the highest standards of any manufacturing sector, non-implanted medical devices vary in this, from airway and blood handling (very high standards); to non-internal but patient contacting; to non-patient contacting equipment.
Components are made by a mix of casting/forging (often automated CNC casting systems) followed by machining and by machining from solid.
Specialist CNC equipment is used for surface texturing (laser etching or laser ablation systems) and for the extreme polishing required for bearing surfaces such as the ball in a hip replacement.
The military sector is a significant user of CNC made parts, across all systems.
There is low cost sensitivity and Mil-spec quality standards are high.
The sensitive nature of much of the supply limits the supplier base and rarely involves outsource beyond national borders of the manufacturer
Transport and infrastructure
Components for infrastructure, transport etc have lower certification standards than aerospace and medical, but still must meet stringent requirements.
These sectors are more open to mid-range equipped suppliers and tend to be more competitive.
Distinct from transport infrastructure, automotive makes extensive use of high volume CNC processing of parts – generally post-processing of forgings and castings for precision areas.
Unlike the previously listed sectors, automotive is generally very price sensitive and much of the work is focussed on high volume, larger subcontract suppliers in long term relationships, so this is a very difficult market for smaller players
General consumer manufacturing
Many sectors in consumer products make use of CNC machined parts (from various equipment types) for prototyping and high volume.
For example, Mac laptops (and others of their product range) are built into machined-from-solid housings.
This is not a technical decision, as the volumes easily justify the investment required for lower cost methods to reduce costs.
The mainstay of high volume manufacture is plastic molds, die casting tools, press/punch tooling and forging tools.
These are produced by various types of G-Code programmed CNC process – milling, turning, wire cutting, spark erosion, laser cutting/ablation etc.
This sector accounts for a significant proportion of the net G-Code CNC production sector.
A wide range of less obvious G-Code programmed CNC equipment is used in product painting, stone cutting, cake decorating and food production.
Examples of G Commands
Each G-Code command line may have a lot of numbers in it, which makes the code look very complex.
In reality, most of the numbers are high precision coordinates.
Commands are generally structured as:
G## X## Y## Z## F##
– where G is the G-Code command.
G00 – fast move to coordinates. This command is usually for the start or end of a program, to get the cutter into place or back to the zero point.
G01 – move straight to the specified coordinates without deviation at specified speed, driving all three axes proportionally to achieve the minimum path. This is the most used command, as it specifies cutter feed speed and path.
G15 and G16 – enable and disable the use of polar coordinates.
G17, G18, G19 – specifies the X, Y or Z plane as the reference for the commands that follow.
G2, G3 – specifies a circular arc on the plane set with G17, G18 or G19. Arcs are controlled by a start, an end and a midpoint.
G81 to G89 – select and run one of these repeatedly used, 9 programmer defined predetermined cycles/subroutines for drilling, tapping, pattern marking etc. These allow common layout patterns/processes to be used in multiple programs on different (but pattern related) parts. Often called Canned or Mini programs.
G90 – instructs the machine to work to absolute coordinates relative to 0,0,0.
G91 – instructs the machine to use relative coordinates from an arbitrary reference point chosen by the programmer:
- The X, Y and Z elements of a line of G-Code specify (cartesian) coordinates for the target point of movement (start and finish of a straight cut will require two lines for the start point and end point).
- The F component is a function command for the speed of the motion.
Additional commands have been added for non-milling/lathe machines, for example an E-command (after F) specifies an amount of FDM filament (or cake frosting!) to extrude.
In addition, the language allows for machine specific commands that are not part of the open source system but relate to specialist machine functions and brands. These are referred to as M-Codes.
Finally, codes that start with D, H or T specify the offsets required for a cut – generally the reference radius of the tool, to place the toolpath center line at the correct distance for the tool to cut as required.
After the commands in a line, a semi-colon can be followed by a comment about the line. The machine ignores everything after a “ ; “
Is G-Code hard to learn?
G-Code is a remarkably well-structured language, so with a few basic learning steps, the newest user can begin to write/edit code directly on a machine interface/keypad. Proficiency takes time, but brings the reward of better outcomes, delivered faster.
Is learning G-Code really necessary?
To run a CNC, it’s not strictly necessary to learn G-Code. But it helps considerably in achieving faster throughput, efficient use of materials and quality outcomes.
How universal is G-Code?
Strictly, the core commands are all common on most applications – but you’ll need more than the core commands, so you will have to broaden your knowledge base when you move to another machine/platform.
What are the complexities in toolpath that are worth understanding?
Toolpaths for maximum efficiency and smooth direction changes are a developing field. There is deep study required, for perfect toolpath programming, and many CAM systems are less than optimal in staying at the leading edge, so there are complexities to master in this aspect.
G-Code is a powerful toolset that is a key skill for anyone looking for a career in machine shop, toolmaking and manufacture.
While it entails over 100 core commands, plus M and D,H,T commands, it is not hard to learn and use.
It’s very open to line by line reading and this enables stepwise understanding developing, simply by studying existing and CAM generated code and by trying out simple programming, simulation and cutting exercises.
Because G-Code has been in service continuously for so long, there is a wealth of tutorials and examples available, to assist the learner.
There are also extensive forums where knowledge is shared and help often given, as experienced hands share their understanding.